Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Data Definition Language: EX. No:01

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 37

EX.

No:01
DATA DEFINITION LANGUAGE

AIM:

INTRODUCTION:
A data definition language is a computer language for defining data structures.
The term was first introduced in relation to the codasy database model where the
scheme of the database was written in a data definition language describing the
records, fields and sets making up the user data model.
SQL:
Initially, DDL was a subset of SQL statements.

CREATE STATEMENT:
Create to make a new database, table, index or stored query. A create
statements in sql creates and object inside of a relational database management
system.

CREATE TABLE:
Perhaps the most common create command is the CREATE TABLE
COMMAND.
The typical usage is
CREATE [TEMPORARY] TABLE [TABLE_NAME] ([Column definition]) [Table
parameters]

SYNTAX:
Create table table name (fieldname datatype,.);

DROP STATEMENTS:
DROP to destroy an existing database, table, index or view. A drop statement in
SQL removes an object from a RDBMS. The types of objects that can be dropped
depend on which RDBMS is being used, but most support the dropping of tables,
users and database.
The typical usage is simply drop object type object name. For example the
command to drop a table named employees would be:
Drop table employees;
SYNTAX:
Drop table table_name;

ALTER STATEMENTS:
Alter _To modify an existing database object. An alter statement in SQL
changes the properties of an object inside of a relational database management
system (RDBMS) . The types of object that can be altered depend on which RDBMS
is being used.
The typical usage is ALTER object type object name parameters for example,
the command to add a column named bubble for an existing table named sink
would be:
ALTER TABLE SINK ADD bubbles INTEGER;
ALTER TABLE SINK DROP column bubbles;
Alter table table_name ADD column column_name datatype.;

TRUNCATE TABLE:
If there is no further use of records store in a table and the structure has to be
retained then the records alone can be deleted.

TRUNCATE STATEMENT:
If there is no further use of records stored in a table and the structure has
to be retained then the records alone can be deleted.
SYNTAX:
Truncate table tablename ;

COMMANDS:
CREATE COMMANDS:
Create table depositor(customername varchar(20),accno varchar(20));
SQL>desc depositor;
Create table loan(branchname varchar(20),loanno varchar(20),amount
number);
SQL>desc loan;
Create table borrower(customername varchar(20),loanno varchar(20));
SQL>desc borrower;

ALTER STATEMENT:
Alter table loan ADD address varchar(20);
SQL>desc loan;

DROP STATEMENT:
Drop table depositor;
SQL>desc depositor;

TRUNCATE STATEMENT:
Truncate table depositor;
SQL>desc depositor;

RESULT:
EX No:02
DATA MANIPULATION LANGUAGE

AIM:

DML:
Data Manipulation Language allows the users to query and manipulate data in
existing schema in object. It allows following data to insert, delete, update, select and
recovery data in schema object.

INSERT
Any values can be inserted into the table using insert command. There are two
types of insert commands. Multiple values can be inserted (using &) and single value
can be inserted (without using &)

SYNTAX
insert into table_name values(&field_name1 datatype,&field_name2
datatype,.......&field_namen datatype);

SELECT
Select command is used to select the records from the table or view.

SYNTAX
Select column_name from table_name;

UPDATE
It allows the user to update the particular column value using the where
condition.

SYNTAX
update tablename set column_name=value where conditon;

DELETE
It allows you to delete the particular column values using where condition.

SYNTAX
delete from tablename where condition;
COMMANDS
1. INSERT

SQL>insert into depositor values (&customer_name,&acc_no);


Enter the value for customer_name:'Hayes'
Enter the value for acc_no:A-102
SQL>/
Enter the value for customer_name:'Jhonson'
Enter the value for acc_no:A-101

SQL>/
Enter the value for customer_name:'Jones'
Enter the value for acc_no:A-217

SQL>/
Enter the value for customer_name:'Lindsay'
Enter the value for acc_no:A-222

SQL>/
Enter the value for customer_name:'Smith'
Enter the value for acc_no:A-215

SQL>/
Enter the value for customer_name:'Turner'
Enter the value for acc_no:A-305

SQL>select * from depositor;

SQL>insert into borrower values (&customer_name,&loan_no);


Enter the value for customer_name:'Hayes'
Enter the value for loan_no:L-15

SQL>/
Enter the value for customer_name:'Jack'
Enter the value for loan_no:L-14

SQL>/
Enter the value for customer_name:'Jones'
Enter the value for loan_no:L-17

SQL>/
Enter the value for customer_name:'Smith'
Enter the value for loan_no:L-11

SQL>/
Enter the value for customer_name:'William'
Enter the value for loan_no:L-18

SQL>/
Enter the value for customer_name:'Adams'
Enter the value for loan_no:L-16
SQL>select * from borrower;

SQL>insert into loan values(&loan_no,&branch_name,&amount);


Enter the value for loan_no:L-11
Enter the value for branch_name:'Roundhill'
Enter the value for amount:900

SQL>/
Enter the value for loan_no:L-11
Enter the value for branch_name:'Roundhill'
Enter the value for amount:900

SQL>/
Enter the value for loan_no:L-14
Enter the value for branch_name:'Downtown'
Enter the value for amount:1500

SQL>/
Enter the value for loan_no:L-15
Enter the value for branch_name:'Perryridge'
Enter the value for amount:1500

SQL>/
Enter the value for loan_no:L-16
Enter the value for branch_name:'Perryridge'
Enter the value for amount:1300

SQL>/
Enter the value for loan_no:L-17
Enter the value for branch_name:'Downtown'
Enter the value for amount:1000

SQL>/
Enter the value for loan_no:L-23
Enter the value for branch_name:'Redwood'
Enter the value for amount:1200

SQL>select * from loan;


2. UPDATE

SQL>update depositor set customer_name='Curry' where acc_no=A-102;

SQL>select * from depositor;

SQL>update loan set branch_name='London' where loan_no=L-16;

SQL>select * from loan;

3.SELECT

SQL>select * from depositor;

4.DELETE

SQL>delete from depositor acc_no=222;

RESULT:
EX.No:3 CREATION OF VIEWS, SYNONYMS, INDEX,
SEQUENCE AND SAVEPOINTS

AIM:

INTRODUCTION:
A view is logical table based on a table or another view and acts as a window
through which data on tables can be viewed or changed. A view does not contain
data. The definition of view is stored in the data dictionary.

ADVANTAGES OF VIEW:
Views restrict access to data because the view can display selective column
from table.
Views can be used to make simple queries to retrieve the results of complicated
queries.

CREATING VIEW:
A view can be created using the following statements.

SYNTAX:
create or replace view viewname as select columnname from tablename where
condition

MODIFYING A VIEW:
With the OR replace option a view can be created even if one exists with this
name already, thus replacing the old version of the view for its owner. This means
that the view can be altered without dropping recreating and re granting object
privileges.

SYNTAX:
create or replace view viewname as select columnname from tablename
where condition;

DROPPING A VIEW:
The view can be remove using the following statements.

SYNTAX:
drop view viewname;
This statement removes the view definition from the database. Dropping view
has no effect on the tables on which the view was based.
SEQUENCES:
A sequence is a user created database object that can be shared by multiple
users to generate unique integers.
CREATING A SEQUENCE:
The following statement is used to create sequence to generate sequential
numbers automatically.

SYNTAX:
create sequence sequence name
[increment by n]
[start with n]
[max value n]
[min value n]
[{cycle/no cycvle}]
[{cache/no cache}]

DROPPING A SEQUENCE:
The following statement is used to remove a sequence from data dictionary.

SYNTAX:
drop sequence sequencename;

INDEX:
An oracle server index is a schema object that can by using a pointer. Indexes
can be created explicitly or automatically. An index provides direct and fast access to
rows in a table.

SYNTAX:
create index indexname on tablename ( columnname ( columnname )....);

REMOVING A INDEX:
We cannot modify indexes to change an index, we have to drop it and recreate
it.

SYNTAX:
drop index indexname;

RENAME INDEX:
This statement is used to rename the index.

SYNTAX:
alter index indexname rename to new indexname;
SYNONYMS:
To refer a table owned by another user,we need to prefix the tablename with
the name of the user who created it followed by a period.

CREATING A SYNONYMS:
A synonyms can be created using the following statements.

SYNTAX:
create[public]synonym synonymname for tablename;

DROPING A SYNONYMS:
To drop a synonym,the following statement is used only the database
adminstrator can drop a public synonym.

SYNTAX:
drop synonym synonymname;

SAVEPOINT:
The savepoint makes names and maked the current point in the processing of
transaction using savepoint with rollback,weekend undo and a part of the transaction
instead of whole transaction.Maximum number of transaction is 5.

SYNTAX:
savepoint savepointname;

COMMANDS:
VIEW:
1.Create view priya as select customername, accno from depositor where
accno='102';
select *from priya;

2.Create view name as select loanno,amount from loan where amount='2000';


select * from name;

3.Create view jahi as select customername,loanno,from borrower where


customername='william';
select * from jahi;

MODIFYING A VIEW:
1.Create or replace view jahi as select customername,accno from depositor
where accno='102';
2.Create or replace view priya as select customername, loanno from borrower
where customername='william';
select * from priya;
DROPPING A VIEW:
1.Sql>Drop view priya;
2.Sql>Drop view name;

INDEX:
1.Create index haj on borrower (customername, loanno);
2.Create index money on depositor(customername, accno);
3.Create index project on loan(loanno, branchname, amount);

RENAME INDEX:
1.Alter index haj rename to order;
2.Alter index project rename to customers;
3.Alter index money rename to item;

DROP INDEX:
1.Drop index order;
2.Drop index item;
3.Drop index customers;

SYNONYM:
1.Create synonym process for depositor;
2.Create synonym krish for borrower;
3.Create synonym vini for loan;

PUBLIC SYNONYM:
1.Create public synonym process for depositor;
2.Create public synonym krish for borrower;
3.Create public synonym vini for loan;

SAVE POINT:
1.Save point table;
2.Save point table1;

SEQUENCE :
1.Create sequence sss;
2.Create sequence aaa;

RESULT:
EX No:04
CONSTRAINTS

AIM:

CONSTRAINTS:
Constraints are part of the table definition that limits and restriction on the
value entered into its columns.

TYPES OF CONSTRAINT
Primary key
Foreign key or Reference key
Check
Unique
Not null
null
default.

CONSTRAINTS CAN BE CREATED IN THREE WAYS


Column level constraints
Table level constraints
Using DDL statements- alter table command.

OPERATIONS ON CONSTRAINTS:
Enable
Disable
Drop

COLUMN LEVEL CONSTRAINTS USING PRIMARY KEY :

SYNTAX:
Create<obj.type><obj.name>(columnname <datatype>(size)<type of
constraints>,column name1<datatype>(size)......);

Example:
SQL> create table employee(empno number(4) primary key,ename varchar(20),job
varchar(20),sal number,deptno number);
COLUMN LEVEL CONSTRAINTS USING PRIMARY KEY:

SYNTAX:
SQL>create <obj.type> <obj.name>(column name1<datatype>(size)
constraints<name of the constraints> <type of the constraints>,column
name1<datatype>(size).......);

QUERY:
SQL>create table employee(empno number(),constraints empno,px,primary
key,ename varchar(20),job varchar(20),number(5),deptno number(7));

COLUMN LEVEL FOREIGN KEY CONSTRAINTS :

SYNTAX:

PARENT TABLE:
SQL>create<obj.type> <obj.name>(column name1<datatype>(size)<type of
constraints>column name1<datatype>(size)......);

SYNTAX:

CHILD TABLE:
SQL>create<obj.type><obj.name>(columnname1<datatype>(size),columnname2<da
tatype>(size)references<table name><column name>......);

QUERY:
SQL>create table dept (dept number(2) primary key dname varchar2(20),location
varchar2(15));
SQL>create table emp 4(empno number(3),deptno number(2) references
dept(deptno),design varchar2(10));

CHECK CONSTRAINTS:

COLUMN LEVEL CHECK CONSTRAINTS:


SYNTAX:
SQL>create<obj.type><obj.name>(columnname1<datatype>(size)constraints<constr
aints name><type of constraints>(constraints criteria),column name 2<data
type>(size));

QUERY:
SQL>create table emp7(empno number(3),ename varchar(20),design
varchar(20),varchar(20),sal number(5) constraints emp7_sal_ck check(sal>500 and
sal<1000),Dept no number(2));

CONSTRAINTS WITH ALTER COMMAND:


SYNTAX:
SQL>create <objtype><objname>(column name1)<datatype>(size),(column
name2)<data type>(size),constraints<constraints name><type of
constraints>(constraints criteria));

QUERY:
SQL>create table emp9(empno number,ename varchar(20),design varchar(15),sal
number(5));

UNIQUE CONSTRAINTS:

SYNTAX:
SQL>create<obj.type><obj.name>(columnname1<datatype>(size)constraint<nameof
constraint> <constraint type>,column name2<datatype>(size));

QUERY:
SQL>create table emp10(empno number(5),ename varchar(20),design varchar(20)
constraint emp10,design_ck unique sal number(5));

NOT NULL:

COLUMN LEVEL CONSTRAINT:

SYNTAX:
SQL>create<obj.type><obj.name>(columnname1<datatype>(size) constraint<name
of constraint><constraint type> column name2<datatype>(size));

QUERY:
SQL>create table emp13(empno number(4),ename varchar(20) constraint emp13
ename nn not null design varchar(20),sal number(3));

NULL:

SYNTAX FOR COLUMN LEVEL CONSTRAINT WITH NULL:


SQL>create <obj.type><obj.name> (column name1<datatype>(size)
constraint<name of constraint><constraint type>,column name2<datatype>(size));

QUERY:
SQL>create table emp13(empno number(4),ename varchar(20) constraint emp13
ename not null design varchar(20),sal number(5));
CONSTRAINT DISABLE/ENABLE:

CONSTRAINT DISABLE:

SYNTAX:
SQL>alter table<table name> disable constraint<constraint name>;

QUERY:
SQL>alter table emp13 disable constraint emp13_ ename_NN null;

CONSTRAINT ENABLE:

SYNTAX:
SQL>alter table <tablename> enable constraint<constraint name>;

QUERY:
SQL>alter table emp13 enable constraint emp13_ename_NN null;

RESULT:
EX No:05
NESTED QUERIES AND JOIN QUERIES

AIM:

INTRODUCTION:

OBJECTIVE:
Sql joins are used to query data from two are more tables, based on a
relationship between certain columns in these tables.

PROCEDURE:

Start
Create a table with its essential attributes
Insert attributes values into the table
Execute different commands and extract information from the table
Stop

COMMANDS:

INNERJOIN:
The innerjoin keyword return rows when there is at least one match in both
tables.

LEFTJOIN:
The leftjoin keyword returns all rows from the left table (table name1),even if
there are no matches in the right table(table name2).

RIGHTJOIN:
The rightjoin keyword return all rows from the right table(table name2),even if
there are no matches in the left table(table name1).

FULLOUTERJOIN:
The fullouterjoin keyword return rows when there is a match in one of the
tables.

SYNTAX:

INNER JOIN:
Sql>select column_name(s) from table_name1 innerjoin table_name2 on
table_name1 column_name=table_name2 column name.

LEFT JOIN:
Sql>select column_name(s) from table_name1 leftjoin table_name2 on
table_name1 column_name=table_name2 column_name.

RIGHTJOIN:
Sql>select column_name(s) from table_name1 rightjoin table_name2 on
table_name1 column_name=table_name2 column_name.

FULLOUTERJOIN:
Sql> select column_name(s) from table_name1 fulljoin table_name2 on
table_name1 column_name=table_name2 Column_name.

COMMANDS:

INNERJOIN:
Sql>select office.orderid, programmer.customername, office.orderdate from
office innerjoin programmer on office.customerid=programmer.customerid;

RIGHTJOIN:
Sql>select customers.customername, office.orderid from customers rightjoin
office on customers.customerid=office.customerid;

LEFTJOIN:
Sql>select programmer.customername, office.orderid from programmer
leftjoin office on programmer.customerid=office.customerid;

FULLOUTERJOIN:
Sql>select customers.customername, office.orderid from customers full outer
join office on customers.customerid=office.customerid;

NESTED QUERIES:
A sub query is best defined as a query within a query. Sub queries enable you
to write queries that select data rows for criteria that are actually developed while the
query is executing at run time. More formally, it is the use of a SELECT statement
inside one of the clauses of another SELECT statement. In fact, a sub query can be
contained inside another sub query, which is inside another sub query, and so forth. A
sub query can also be nested inside INSERT, UPDATE, and DELETE statements.
Sub queries must be enclosed within parentheses.

TYPES OF SUBQUERIES:

Single Row Sub Query: Sub query which returns single row output. They mark the
usage of single row comparison operators, when used in WHERE conditions.
Multiple row sub query: Sub query returning multiple row output. They make use
of multiple row comparison operators like IN, ANY, ALL. There can be sub queries
returning multiple columns also.

Correlated Sub Query: Correlated subqueries depend on data provided by the outer
query.This type of subquery also includes subqueries that use the EXISTS operator to
test the existence of data rows satisfying specified criteria.

DISPLAY ALL CONTENT FROM CUST_NAME 'JO'


SOL>select * from depositor where loan_no=(select loan_no from depositor where
cust_name='jo');

DISPLAY THE NAME WHERE AMOUNT=1000


SQL>select cust_name from depositor where loan_no=(select loan_no from depositor
where amounts=1000);

DISPLAY ALL CONTENT FROM ACTION=A201


SQL>select * from depositor where amounts=(select amounts from depositor where
actions='A201');

RESULT:
EX No:06
STUDY OF PL/SQL BLOCK

AIM:

INTRODUCTION:
PL/SQL stands for procedural language extension of SQL.PL/SQL is a
combination of SQL along with the procedural features of programming languages.
It was developed by oracle corporation in the early 90's to enhance the
capabilities of SQL.

THE PL/SQL ENGINE:


Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL
code can be stored in the client system (client-side) or in the database(sever-
side).

PL/SQL BLOCK CONSISTS OF THREE SECTIONS:


The declaration section (optional).
The execution section (mandatory).
The exception (or error) handling section (optional).

DECLARATION SECTION:
The declaration section of a PL/SQL block starts with the reserved
keyword DECLARE. This section is optional and is used to declare any
placeholders like variables, constants, records and cursors, which are used to
manipulate data in the execution section. Placeholders may be any of variables,
constants and records, which stores data temporarily. Cursors are also declared in
this section.

EXECUTION SECTION:
The execution section of a PL/SQL block starts with the reserved
keyword BEGIN and ends with END. This is a mandatory section and is the
section where the program logic is written to perform any task. The
programmatic constructs like loops, conditional statement and SQL statements
from the part of execution section.

EXCEPTION SECTION:
The exception section of a PL/SQL block starts with the reserved
keyword EXCEPTION. This section is optional. Any errors in the program can
be handled in this section, so that the PL/SQL blocks terminates gracefully. If
the PL/SQL block contains exceptions that cannot be handled , the block
terminates abruptly with errors.
Every statement in the above three sections must end with a
semicolon(;).PL/SQL blocks can be nested within other PL/SQL blocks.
Comments can be used to document code.

PL/SQL GENERAL SYNTAX:

SQL>DECLARE
<Variable declaration>;
Begin
<Executable statement>;
End;
/

PL/SQL PROGRAMME:

Declare
A number;
B number;
C number;
Begin
A:=10;
B:=20;
C:=A+B;
Dbms_output.put_line(sum is:||c;
End;
/

RESULT:
EX No:07
CONTROL STRUCTURES

AIM:

Objective:
PL/SQL control structure provides conditional tests, loops, flow control and
branches that let to produce well-structured programs.

PROCEDURE:
step1: start
step2: initialize the necessary variables
step3: develope the set of statements with the essential operational
parameters.
step4: specify the individuval operation to be carried out
step5: execute the statements
step6: stop.

PL/SQL GENERAL SYNTAX


SQL>declare
<variable declatation>;
begin
<execute statements>;
end;

PL/SQL program for IF condition

PROCEDURE:
step 1: start
step 2: initilize the if condition
step 3: invoke the if condition
step 4: execute the statements
step 5: stop

PL/SQL GENERAL SYNTAX FOR IF CONDITION


SQL>declare
<variable declatation>;
begin
if(condition)then
<execute statements>;
end;
Coding for if Statement
DECLARE
b number;
c number;
BEGIN
b:=10;
c:=20;
if(c>b)THEN
dbms_output.put_line('c is maximum');
end if;
end;
/

PL/SQL GENERAL SYNTAX FOR IF ELSE CONDITION


SQL>declare
<variable declatation>;
begin
if(condition)then
<statements>;
else
<statements>;
end if;
end;

Coding for if else Statement


DECLARE:
n number;
BEGIN
dbms_output.put_line('enter a number');
n:=&number;
if(n<5) THEN
dbms_output.put_line('number less than five');
else
dbms_output.put_line('number greater than five');
end if;
end;
/
PL/SQL GENERAL SYNTAX FOR NESTED IF CONDITION
SQL>declare
<variable declatation>;
begin
if(condition)then
<statements>;
else if
<statements>;
else
<statements>;
end if;
end;

Coding for Nested if Statement


a number;
b number;
c number;
begin
a:=&a;
b:=&b;
c:=&c;
if(a>b)and(a>c)then
dbms_output.put_line('A is Maximum');
else if(b>a)and(b>c)then
dbms_output.put_line('B is Maximum');
else
dbms_output.put_line('C is Maximum');
end if;
end;

PL/SQL GENERAL SYNTAX FOR LOOPING STATEMENT


SQL>declare
<variable declatation>;
begin
loop
<statements>;
end loop;
<execute statements>
end;
PL/SQL GENERAL SYNTAX FOR "for" LOOPING STATEMENT
SQL>declare
<variable declatation>;
begin
for(start value...end value)
loop
<statements>;
end loop;
<execute statements>
end;

Coding for "for" Loop


Declare
n number;
Sum1 number default 0;
endvalue number;
begin
endvalue:=&endvalue;
n:=1;
for n in 1..endvalue
loop
if mod(n,2)=1
then
sum1:=sum1+n;
end if;
end loop;
dbms_output.put_line('sum='||sum1);
end;
/

PL/SQL GENERAL SYNTAX WHILE LOOPING STATEMENT


SQL>declare
<variable declatation>;
begin
while
loop
<statements>;
end loop;
<execute statements>
end;

Coding for "while" Loop


Declare
n number;
sum1 number default 0;
hh number;
begin
hh:=&hh;
n:=1;
while(n<hh)
loop
sum1:=sum1+n;
n:=n+2;
end loop;
dbms_output.put_line('sum of odd numbers= '||sum1);
end;
/

RESULT:
EX No:08
EXCEPTIONS

AIM:

EXCEPTION:
An error condition during a program execution is called an exception in
PL\SQL.PL\SQL supports programmers to catch such conditions using EXCEPTION
block in the program and appropriate action is taken against the error condition.

There are two types of exceptions:


System-defined exceptions
User-defined exceptions

SYNTAX FOR EXCEPTION HANDLING:


The general syntax for exception handlings is as follows. Here you can list down
as many as exceptions you want to handle. The default exception will be handled
using WHEN others THEN:
DECLARE
<declarations section>
BEGIN
<executable commands(s)>
EXCEPTION
<exception handling goes here>
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
WHEN exception3 THEN
exception3-handling-statements
..................
WHEN others THEN
exception3-handling-statements
END;

EXAMPLE:
Let us write some simple code to illustrate the concept. We will be using the
CUSTOMERS table we had created and used in the previous chapters:

DECLARE
c_id customers.id%type:=8;
c_name customers.name%type;
c_addr customers.address%type;
BEGIN
SELECT name,address INTO c_name,c_addr
FROM CUSTOMERS
WHERE id=c_id;
DBMS_OUTPUT.PUT_LINE('Name:'||c_name);
DBMS_OUTPUT.PUT_LINE('Address:'||c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
The above program displays the name and address of a customer whose ID is given.
Since there is no customer with ID value 8 in our database, the program raises the
run-time exception NO_DATA_FOUND, which is captured in EXCEPTION block.

RAISING EXCEPTIONS:
Exceptions are raised by the database server automatically whenever there is
any internal database error, but exceptions can be raised explicitly by the programmer
by using the command RAISE.
Following is the syntax of raising an exception:

DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
WHEN exceptionn_name THEN
statement;
END;
You can use above syntax in raising oracle standard exception or any user-
defined exception. Next section will give you an example on raising user-defined,
similar way you can raise oracle standard exceptions as well.
USER-DEFINED EXCEPTIONS:
PL/SQL allows you to define your own exceptions according to the need of
your program. A user-defined exception must be declared and then raised explicitly,
using either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.

The syntax for declaring an exception is:


my-exception EXCEPTION;

EXAMPLE:
The following example illustrates the concept. This program asks for a
customer ID, when the user enters an invalid ID, THE EXCEPTION INVALID_ID IS
RAISED.

PROGRAM:
DECLARE
c_id customers.id%type:=&cc_id;
c_name customers.name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id<=0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name,address INTO c_name,c_addr
FROM customers
WHERE id=c_id;
DBMS_OUTPUT.PUT_LINE ('Name:'||c_name);
DBMS_OUTPUT.PUT_LINE ('Address:'||c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
RESULT:
EX No:09
PROCEDURES

AIM:

ALGORITHM:
Step 1: Start
Step 2: Create a table with table name pro
Step 3: Get the, b, c, d value from the user
Step 4: Then compare if a greater than b then c equal to mod (a,b) and print the result
Step 5: OR compare if a less than b then d equal to 0 then print the result
Step 6: Display the suitable result
Step 7: End

EXECUTION:
Setting serveroutput on
SQL> set serveroutput on

PROGRAM:

PROCEDURE USING POSITIONAL PARAMETER


SQL> set serveroutput on
SQL> create procedure proc4 as
2 begin
3 dbms_output.put_line('Hello from procedure');
4 end;
5 /

PROCEDURE USING NOTATIONAL PARAMETER


SQL> set serveroutput on
SQL> create procedure proc6
2 (n1 in number, n2 in number, tot out number)is
3 begin
4 tot: =n1+n2;
5 end;
6/
PROCEDURE FOR GCD NUMBER
SQL> create procedure pro1
2 is
3 a number (3);
4 b number (3);
5 c number (3);
6 d number (3);
7 begin
8 a: =&a;
9 b: =&b;
10 if (a>b) then
11 c: =mod (a,b);
12 if(c=0) then
13 dbms_output.put_line('GCD is');
14 dbms_output.put_line(b);
15 else
16 dbms_output.put_line('GCD is');
17 dbms_output.put_line(c);
18 end if;
19 else
20 d:=mod(a,b);
21 if(d=0) then
22 dbms_output.put_line('GCD is');
23 dbms_output.put_line(a);
24 else
25 dbms_output.put_line('GCD is');
26 dbms_output.put_line(d);
27 end if;
28 end if;
29* end;
30 /

RESULT:
EX No:10
TRIGGERS AND FUNCTIONS

AIM:

TRIGGERS:

THEORY:
A data base trigger is stored pl/sql. Program unit associated with a specific
database table or view. The code in the trigger defines the action the database needs
to perform whenever some database manipulation (Insert, Update, and Delete) takes
place.
A database trigger has three parts,
1. Trigger Event.
2. A Trigger Constraint.
3. Trigger Action.

PROCEDURE:
1.Start.
2.Initialize the trigger with specific table id.
3.Specify the operations (Update, Delete, Insert) for which trigger has to be executed.
4.Execute the trigger procedure for both before and after sequences.
5.Carry out the operation on the table to check for trigger execution.
6.Stop.

FUNCTIONS:

PROCEDURE:
1. Start.
2. Create the table with essential attributes.
3. Initialize the functions to carry out the searching procedure.
4. Frame the searching procedure for both positive and negative searching.
5. Execute the function for both positive and negative result.
6. Stop.
SYNTAX FOR TRIGGERS:
The syntax for creating a trigger is:

CREATE[or Replace] TRIGGER trigger_name


{Before|After|Instead of}
{Insert [or]|Update[or]|Delete}
[of col_name]
ON table_name
[Referencing old As o new As n]
[For each row]
DECLARE
declaration_statements
BEGIN
Executable_statements
EXCEPTION
Exception_handling_statements
END;

EXECUTION:
1.Create a trigger to pop_up the DML operations:

SQL>create table order(id int,name varchar(20),income int,savings int);


a)SQL>insert into order values(2,'Rubiya',20000,6500);
b)SQL>insert into order values(3,'Keerthana',2500,1000);
c)SQL>insert into order values(4,'Julanta',5000,4100);
d)SQL>select *from order;

TYPE 1: TRIGGER AFTER UPDATE


Create or replace trigger t
After
Insert OR
Update of salary, department_id OR
Delete
ON employees
Begin
Case
When inserting then
dbms_output.put_line(Inserting);
When Updating(Salary) then
dbms_output.put_line(Updating Salary);
When Updating(Department_id) then
dbms_output.put_line(Updating Department ID);
When deleting then
dbms_output.put_line(Deleting);
Endcase;
End;
/

1)SQL>update employees set salary=1700 where dept_id=1;


2)SQL>insert into employees values(15000,101);
3)SQL>delete from employee where dept_id=2;

TYPE 2: TRIGGER BEFORE UPDATE


Create or replace trigger t
Before
Insert OR
Update of salary, department_id OR
Delete
ON employees
Begin
Case
When inserting then
dbms_output.put_line(Inserting);
When Updating(Salary) then
dbms_output.put_line(Updating Salary);
When Updating(Department_id) then
dbms_output.put_line(Updating Department ID);
When deleting then
dbms_output.put_line(Deleting);
Endcase;
End;
/

1)SQL>insert into employees values(100000,105);


2)SQL>update employees set dept_id=5 where salary=1700;
3)SQL>delete from employees where dept_id=5;

EXECUTION:
set serveroutput on
SQL>set serveroutput on
IMPLEMENTATION OF FACTORIAL USING FUNCTION:
SQL>create function fnfact(n number) return number is b number;
begin
b:=1;
for i in 1..n
loop
b:=b*i;
end loop;
return b;
end;
/
SQL>declare
n number:=&n;
y number;
begin
y:=fnfact(n);
dbms_output.put_line(y);
end;
/
PROGRAM:
1)SQL>create table phonebook(phone_no number(6) primary key,username varchar
(20),doorno varchar 2(20),street varchar2(20),place varchar2(30),pincode char(6));

SQL>insert into phonebook values('20132','vijay','120/5D','Sweet Street','NGO


colony','650000');

SQL>insert into phonebook values ('29457','vasanth','95/RS','Daniel Street','POG


colony','650002');
SQL>select *from phonebook;
2)SQL>create or replace function findaddress(phone in number)return varchar2
address varchar2(100);
begin
select username ||','||doorno||','||street||','||place||',||pincode into address
from phonebook where phone_no=phone;
return address;
exception
when no_data_found then return 'address not found';
end;
/

3) SQL>declare
address varchar2(100);
begin
address:=find address(20312);
dbms_output.put_line(address);
end;
/
SQL>declare
address varchar2(100);
begin
address:=find address(23556);
dbms_output.put_line(address);
end;
/

RESULT:
EX.No: 11 MINI PROJECT PERSONAL INFORMATION
SYSTEM

AIM:

ALGORITHM:
1. Forms should be designed with appropriate controls.
2. Database connection is to be made.
3. For, each control, code the corresponding procedure.
4. Execute & display the output form.
5. Perform Database manipulation using form.
CODING:
using System.Data.OleDb;
OleDbConnection con;
OleDbCommand cmd;
private void button1_Click(object sender, EventArgs e)
{
cmd.Connection = con;
cmd.CommandText = "insert into student details
values(?,?,?,?,?,?)";
cmd.Parameters.Add("regno", textBox1.Text.Trim());
cmd.Parameters.Add("name",textBox2.Text.Trim());
cmd.Parameters.Add("year", comboBox2.Text);
cmd.Parameters.Add("dept", comboBox1.Text);
cmd.Parameters.Add("conno",int.Parse(textBox4.Text.Trim()));
cmd.Parameters.Add("email", textBox5.Text.Trim());
cmd.ExecuteNonQuery();
cmd.Dispose();
MessageBox.Show("Record Inserted...");
textBox1.Clear();
textBox2.Clear();
textBox4.Clear();
textBox5.Clear();
comboBox1.Text = "SELECT DEPT";
comboBox2.Text = "SELECT YEAR";
}
private void button7_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button6_Click(object sender, EventArgs e)
{
textBox1.Clear();
textBox2.Clear();
textBox4.Clear();
textBox5.Clear();
comboBox1.Text = "SELECT DEPT";
comboBox2.Text = "SELECT YEAR";
}
private void Form1_Load(object sender, EventArgs e)
{
con = new OleDbConnection();
con.ConnectionString = "Provider=MSDAORA;Data
Source=orcl;Persist Security Info=True;Password=vvcoe;User
ID=EvansRaja";
con.Open();
cmd = new OleDbCommand();
}
private void button3_Click(object sender, EventArgs e)
{
cmd.Connection = con;
cmd.CommandText = "select * from studentdetails where
regno=?";
cmd.Parameters.Add("regno", textBox1.Text.Trim());
OleDbDataReader rs = cmd.ExecuteReader();
if (rs.Read())
{
textBox1.Text = rs.GetString(0);
textBox2.Text = rs.GetString(1);
comboBox2.SelectedItem = rs.GetString(2);
// MessageBox.Show(rs.GetString(2));
comboBox1.SelectedItem = rs.GetString(3);
textBox4.Text = rs.GetValue(4).ToString();
textBox5.Text = rs.GetString(5);
}
rs.Close();
cmd.Dispose();
}
private void button4_Click(object sender, EventArgs e)
{
cmd.Connection = con;
cmd.CommandText = "update studentdetails set
regno=?,name=?,year=?,dept=?,conno=?,email=? where regno=?";
cmd.Parameters.Add("regno", textBox1.Text.Trim());
cmd.Parameters.Add("name", textBox2.Text.Trim());
cmd.Parameters.Add("year", comboBox2.Text);
cmd.Parameters.Add("dept", comboBox1.Text);
cmd.Parameters.Add("conno",int.Parse(textBox4.Text.Trim()));
cmd.Parameters.Add("email", textBox5.Text.Trim());
cmd.Parameters.Add("regno", textBox1.Text.Trim());
cmd.ExecuteNonQuery();
cmd.Dispose();
MessageBox.Show("Record Updated...");
}

private void button2_Click(object sender, EventArgs e)


{
cmd.Connection = con;
cmd.CommandText ="delete from studentdetails whereregno=?";
cmd.Parameters.Add("regno", textBox1.Text.Trim());
cmd.ExecuteNonQuery();
cmd.Dispose();
MessageBox.Show("Record Deleted...");
textBox1.Clear();
textBox2.Clear();
textBox4.Clear();
textBox5.Clear();
comboBox1.Text = "SELECT DEPT";
comboBox2.Text = "SELECT YEAR";
}

RESULT:

You might also like