Professional Documents
Culture Documents
COURSE MATERAL
For
PL-SQL
It is called third generation programming language, since it contains all the standard rules of
programming.
Difference between SQL and PL/sQL is, SQL is called Non-Procedural language since it deals with only
WHAT data to be extracted, whereas PL/SQL is called Procedural language, since it deals with WHAT
data to be extracted and HOW it should be displayed.
1. Anonymous block programming : A program which is written in nameless block. This program will be
residing in Operating system since it is created in .sql file.
2. Stored block programming : A program which is written in named block and resides in database server.
It includes Stored procedures, Stored functions, Stored packages and Triggers.
Advantages of PL/SQL:
1. Supports for SQL : DDL, DML, TCL, DQL, pseudo columns, functions which are used at SQL, the
same can be used in PL/SQL.
2. Better performance : At SQL only 1 command is sent for execution to a server whereas at PL/SQL
group of commands are stored in the form of a block and can send them for execution at once to a server,
by which performance of application gets increases.
3. Portability : The program which is written in PL/SQL on one platform can easily be transfered to the
other platform.
4. Tight Integration with SQL: Datatypes used at SQL, the same can be used at PL/SQL. It also
provides the new datatype called Composite datatypes which includes 2 datatypes; %TYPE ,
%ROWTYPE
6. Modularity : A large application program can get split into small modules or blocks.
This program is created in .sql file and will be available at operating system.
1. Declaration block
2. Execution block
3. Exception block
1. Declaration block: At this block it allows a user to declare normal variables, constant variables,
objects. This block is identified by a keyword called DECLARE.
2. Execution block: At this block it allows a user to write all those statements by which program gets
executed. This block is identified by a keyword called BEGIN.
3. Exception block: At this block it allows a user to handle runtime errors. It is identified by a keyword
called EXCEPTION.
syntax:
[DECLARE
declaration part;]
BEGIN
exection part;
[EXCEPTION
exception handlers;]
END;
1. NUMBER
2. CHAR
3. VARCHAR2
3
4. DATE
5. BOOLEAN : It is used only in PL/SQL program, which allows a user to store boolean value i.e. TRUE
or FALSE.
It performs 2 tasks;
1. Displays Messages.
2. Before executing a program it is essential that the environment variable SERVEROUTPUT should be
set to ON.
SQL> @file_name
BEGIN
DBMS_OUTPUT.PUT('WELCOME');
DBMS_OUTPUT.PUT_LINE('THANX');
END;
OPERATORS:
. Access Operator
:= Assignment Operator
|| Concatination Operator
** Exponentiation Operator
.. Range Operator
DECLARE
a NUMBER:=10;
b NUMBER:=39;
c NUMBER;
BEGIN
c:=a+b;
DBMS_OUTPUT.PUT_LINE(c);
DBMS_OUTPUT.PUT_LINE('SUM IS.....'||c);
DBMS_OUTPUT.PUT_LINE(a+b);
END;
OUTPUT:
168
SUM IS.....168
76 + 92 = 168
168
DECLARE
a NUMBER:=&a;
b NUMBER:=&b;
c NUMBER;
BEGIN
c:=a+b;
DBMS_OUTPUT.PUT_LINE('SUM IS.....'||c);
END;
CONSTANT VARIABLES:
Declaration of constant variables and initialization should be carried out simultaneously. A constant
variables cant be modified. Any number of constant variables can be declared in a single program.
Syntax:
example:
DECLARE
a CONSTANT NUMBER(3):=89;
BEGIN
DBMS_OUTPUT.PUT_LINE(a);
END;
DECLARE
r NUMBER:=&r;
pi CONSTANT NUMBER:=3.14;
aoc NUMBER;
BEGIN
-- aoc:=pi*r*r;
-- aoc:=pi*POWER(r,2);
aoc:=pi*r**2;
END;
IF CONDITIONAL STATEMENTS:
This conditional statement in pl/sql is used to compare the data providing the result on boolean
expression i.e. TRUE or FALSE.
1. Simple If:
This IF conditional statement allows to write 1 true and 1 false statement or block.
Syntax:
IF condition THEN
true statement;
ELSE
false statement;
END IF;
DECLARE
a NUMBER:=&a;
b NUMBER:=&b;
BEGIN
IF a>b THEN
DBMS_OUTPUT.PUT_LINE('A IS BIG');
ELSE
DBMS_OUTPUT.PUT_LINE('B IS BIG');
END IF;
END;
Write a program to check whether a given number has perfect square or not?
DECLARE
n NUMBER:=&n;
s NUMBER;
BEGIN
s:=TRUNC(SQRT(n));
IF s*s=n THEN
ELSE
DBMS_OUTPUT.PUT_LINE('SORRY');
END IF;
END;
Syntax 1: Syntax 2:
statements; statements;
ELSE statements;
statements; statements;
statements;
END IF;
END IF;
END IF;
Write a program to find the biggest of 2 numbers or display that both are equal?
10
DECLARE
a NUMBER:=&a;
b NUMBER:=&b;
BEGIN
IF A=B THEN
ELSE
IF a>b THEN
DBMS_OUTPUT.PUT_LINE('A IS BIG');
ELSE
DBMS_OUTPUT.PUT_LINE('B IS BIG');
END IF;
END IF;
END;
Write a program to find the biggest of 3 numbers or display that 3 valeus are equal?
DECLARE
a NUMBER:=&a;
b NUMBER:=&b;
c NUMBER:=&c;
BEGIN
11
DBMS_OUTPUT.PUT_LINE('A IS BIG');
DBMS_OUTPUT.PUT_LINE('B IS BIG');
ELSE
DBMS_OUTPUT.PUT_LINE('C IS BIG');
END IF;
END;
Syntax:
IF condition1 THEN
statements;
IF condition2 THEN
statements;
ELSE
statements;
END IF;
ELSE
statements;
12
END IF;
Write a program to check whether a given number is odd or even only for +VE numbers?
DECLARE
n NUMBER:=&n;
BEGIN
IF n>0 THEN
DBMS_OUTPUT.PUT_LINE('IT IS +vE');
IF MOD(n,2)=0 THEN
DBMS_OUTPUT.PUT_LINE('IT IS EVEN');
ELSE
DBMS_OUTPUT.PUT_LINE('IT IS ODD');
END IF;
ELSE
DBMS_OUTPUT.PUT_LINE('IT IS -VE');
END IF;
END;
GOTO statement
It is called branching statement, since it supports to transfer the control from 1 part of a program
to the other part of a program.
1. Label Assignment
2. Label Definition
13
GOTO label_name;
<<label_name>>
statements;
example:
BEGIN
DBMS_OUTPUT.PUT_LINE('WELCOME');
GOTO X;
<<Y>>
DBMS_OUTPUT.PUT_LINE('FIVE');
DBMS_OUTPUT.PUT_LINE('SEVEN');
GOTO Z;
<<X>>
DBMS_OUTPUT.PUT_LINE('NINE');
GOTO Y;
<<Z>>
DBMS_OUTPUT.PUT_LINE('THANX');
END;
OUTPUT:
WELCOME
14
NINE
FIVE
SEVEN
THANX
LOOPING CONSTRUCTS
2. WHILE loop
3. FOR loop
This looping construct will repeat the execution of 1 or more statements only when the given
condition is false.
syntax:
LOOP
statements;
statements;
END LOOP;
This looping construct will terminate its working thru EXIT keyword when the given condition
becomes true.
Write a program to display 1st five natural numbers using the above looping construct?
DECLARE
15
x NUMBER;
BEGIN
x:=1;
LOOP
DBMS_OUTPUT.PUT_LINE(x);
x:=x+1;
END LOOP;
END;
DECLARE
x NUMBER;
BEGIN
x:=1;
LOOP
DBMS_OUTPUT.PUT_LINE(x);
x:=x+1;
END LOOP;
END;
16
This looping construct will support to execute 1 or more statements repeatedly until a condition is
satisfied.
Syntax:
WHILE condition
LOOP
statement 1;
statement 2;
......
statement n;
END LOOP;
DECLARE
x NUMBER;
BEGIN
x:=1;
WHILE x<=5
LOOP
DBMS_OUTPUT.PUT_LINE(x);
x:=x+1;
END LOOP;
END;
17
DECLARE
x NUMBER;
n NUMBER:=&n;
BEGIN
x:=1;
WHILE x<=n
LOOP
DBMS_OUTPUT.PUT_LINE(x);
x:=x+1;
END LOOP;
END;
DECLARE
x NUMBER;
n NUMBER:=&n;
BEGIN
x:=1;
WHILE x<=n*2
LOOP
DBMS_OUTPUT.PUT_LINE(x);
x:=x+2;
18
END LOOP;
END;
DECLARE
n NUMBER:=&n;
i NUMBER;
p NUMBER;
BEGIN
i:=1;
WHILE i<=10
LOOP
p:=n*i;
i:=i+1;
END LOOP;
END;
19
This looping construct will support to execute 1 or more statements based on given range of
values.
Variable used at FOR looping construct does not required its declaration.
Variable will act like a local variable, which means it works only in that block where it is used.
Syntax:
LOOP
statement 1;
statement 2;
.......
statement n;
END LOOP;
When REVERSE option is used it will make a loop work in reverse order.
Examples:
1. Write a program to display 1st 5 natural numbers using FOR looping construct?
BEGIN
FOR i IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
20
2. Write a program to display 1st n natural numbers using FOR looping construct?
DECLARE
n NUMBER:=&n;
BEGIN
FOR i IN 1..n
LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(i);
END LOOP;
END;
DECLARE
str VARCHAR2(12):='&str';
21
rev VARCHAR2(12);
BEGIN
rev:=' ';
LOOP
rev:=rev||SUBSTR(str,i,1);
END LOOP;
END;
DECLARE
str VARCHAR2(12):='&str';
rev VARCHAR2(12);
BEGIN
rev:=' ';
LOOP
rev:=rev||SUBSTR(str,i,1);
END LOOP;
IF str=LTRIM(rev) THEN
DBMS_OUTPUT.PUT_LINE('IT IS PALINDROME');
22
ELSE
DBMS_OUTPUT.PUT_LINE('SORRY');
END IF;
END;
DECLARE
str VARCHAR2(12):='&str';
v NUMBER;
c NUMBER;
BEGIN
v:=0;
c:=0;
FOR i IN 1..LENGTH(str)
LOOP
v:=v+1;
ELSE
c:=c+1;
END IF;
END LOOP;
23
END;
SELECT:
This command will retrieve the data from a database into buffer variables.
It supports to retrieve data of all the columns or required columns from a table.
Syntax:
FROM <table1[,table2,table3,..........]>
WHERE condition(s)
GROUP BY col1[,col2,col3,.........]
HAVING condition(s);
COMPOSITE DATATYPES:
1. %TYPE : This composite datatype will support to get the datatype and size of a column to a program
variable. If any changes are made to the logical structure of a table, the program will remain independent
of those changes.
Syntax:
var table_name.column_name%TYPE[:=val/variable];
24
1. Write a program to retrieve the data of a given employee number w.r.to ename,sal and deptno?
DECLARE
eno emp.empno%TYPE:=&eno;
en emp.ename%TYPE;
pay emp.sal%TYPE;
dno emp.deptno%TYPE;
BEGIN
END;
2. %ROWTYPE : This composite datatype will support to store 1 row which is extracted from a table. The
row extracted gets accessed using columns names of a table preceeded by variable.
Syntax:
var table_name%ROWTYPE;
Example:
DECLARE
eno emp.empno%TYPE:=&eno;
erec emp%ROWTYPE;
BEGIN
END;
25
INSERT:
Write a program to insert a new record which includes empno,ename,sal and deptno?
DECLARE
eno emp.empno%TYPE:=&eno;
en emp.ename%TYPE:='&en';
pay emp.sal%TYPE:=&pay;
dno emp.deptno%TYPE:=&dno;
i NUMBER;
j NUMBER;
BEGIN
DBMS_OUTPUT.PUT_LINE('INVALID DEPTNO');
DBMS_OUTPUT.PUT_LINE('INVALID SALARY');
26
ELSE
COMMIT;
END IF;
END;
UPDATE:
Write a program to update the salary by incrementing only if salary is more than 500 and if
employee exists?
DECLARE
eno emp.empno%TYPE:=&eno;
incr NUMBER(7):=&incr;
i NUMBER;
BEGIN
IF i=0 THEN
DBMS_OUTPUT.PUT_LINE('INVALID INCREMENT');
ELSE
COMMIT;
27
END IF;
END;
DELETE:
1. Write a program to delete a record from emp table based on given employee number if the
employee exists?
DECLARE
eno emp.empno%TYPE:=&eno;
i NUMBER;
BEGIN
IF i=0 THEN
ELSE
COMMIT;
END IF;
END;
2. Write a program to delete the rows from emp table based on given department number?
DECLARE
28
dno emp.deptno%TYPE:=&dno;
i NUMBER;
BEGIN
IF i=0 THEN
ELSE
COMMIT;
END IF;
END;
SQL ATTRIBUTES
1. SQL%ROWCOUNT : This attribute returns the number of rows affercted by the DML transaction.
It returns TRUE when DML transaction affects the table else returns with FALSE.
3. SQL%NOTFOUND : This attribute returns boolean value i.e. true or false. It returns TRUE when DML
transaction does not affect the table else returns with FALSE.
example:
Write a program to delete the rows from emp table based on given department number?
DECLARE
29
dno emp.deptno%TYPE:=&dno;
r BOOLEAN;
BEGIN
r:=SQL%FOUND;
IF r=TRUE THEN
ELSE
END IF;
END;
DECLARE
dno emp.deptno%TYPE:=&dno;
r BOOLEAN;
BEGIN
r:=SQL%NOTFOUND;
IF r=TRUE THEN
ELSE
30
END IF;
END;
EXCEPTION HANDLING
Types of Errors:
1. Compile time errors : These errors will occur when the program gets compiled. It generates errors in
those instructions of a program, which are not written as per the provided rules. Hence these errors are
called Syntax Errors.
2. Logical Errors : Required Output and generated output when does not get match, such type of errors
are called Logical Errors.
3. Runtime Errors : These errors occur when the program is in execution. When these errors occur the
program gets terminated inbetween the execution. To handle such runtime errors and have smooth
execution of a program the concept of Exception handling is used.
1. Predefined Exceptions
1. Predefined Exceptions
----------------------------------------------------------------------------
----------------------------------------------------------------------------
number is divided by 0.
31
Note:
1. Exception should be handled under EXCEPTION block, based on the following syntax.
EXCEPTION
statements;
32
3. When Runtime error occurs control automatically gets transfered to EXCEPTION block, searches for
the related exception and handles that exception.
4. Exception block can handle more than 1 exception, based on runtime error related exception will get
handle.
5. All the other unknown runtime errors which may occur in a program can be handled using OTHERS
exception.
6. When exceptions are raised using OTHERS exception, and if related exceptions are also enclosed
then priority is given to related exception.
7. When related exceptions and OTHERS exception is placed in a single program, it is with a rule that first
related exception should be enclosed and then the OTHERS exception should be written.
examples:
DECLARE
a NUMBER:=&a;
b NUMBER:=&b;
c NUMBER;
BEGIN
c:=a/b;
DBMS_OUTPUT.PUT_LINE('QUOTIENT IS ......'||c);
EXCEPTION
END;
33
2. Write a program to input salary and display empno,ename,job,deptno from emp table? Handle
necessary exceptions.
DECLARE
pay emp.sal%TYPE:=&pay;
eno emp.empno%TYPE;
en emp.ename%TYPE;
des VARCHAR2(5);
dno emp.deptno%TYPE;
BEGIN
EXCEPTION
DBMS_OUTPUT.PUT_LINE('MEM INSUFFICIENT');
END;
(OR)
DECLARE
pay emp.sal%TYPE:=&pay;
34
eno emp.empno%TYPE;
en emp.ename%TYPE;
des VARCHAR2(5);
dno emp.deptno%TYPE;
BEGIN
EXCEPTION
END;
1. Declaration of exception
2. Raising of exception
1. Declaration of Exception:
Exception name should be declared at the declaration block of PL/SQL program. Any number of
exception names can be declared but with unique names. A keyword called EXCEPTION should be used
after the exception name.
35
Syntax:
DECLARE
exception_name EXCEPTION;
2. Raising an Exception :
Syntax:
RAISE exception_name;
Syntax:
statements;
Write a program to divide 2 numbers and handle the exception using user defined exception?
DECLARE
a NUMBER:=&a;
b NUMBER:=&b;
c NUMBER;
ZD EXCEPTION;
BEGIN
IF b=0 THEN
RAISE ZD;
END IF;
36
c:=a/b;
DBMS_OUTPUT.PUT_LINE('QUOTIENT IS......'||c);
EXCEPTION
WHEN ZD THEN
END;
Write a program to perform operations over bank and handle necessary exceptions?
BANK
TRANS
37
DECLARE
ano bank.acno%TYPE:=&ano;
trty trans.tt%TYPE:='&trty';
amount trans.amt%TYPE:=&amount;
s bank.bal%TYPE;
OVR_DRFT EXCEPTION;
INV_TRANS EXCEPTION;
INV_AMT EXCEPTION;
BEGIN
ELSE
IF amount>s THEN
RAISE OVR_DRFT;
ELSE
IF amount>s-500 THEN
RAISE INV_TRANS;
38
ELSE
IF amount<100 THEN
RAISE INV_AMT;
ELSE
END IF;
END IF;
END IF;
ELSE
END IF;
END IF;
EXCEPTION
39
END;
PRAGMA EXCEPTIONS
3. PRAGMA exceptions are declared immediately after the declaration of user defined exception name.
4. Any number of PRAGMA exceptions can be declared in a single program,but with their related user
defined exception names.
Syntax:
exception_name EXCEPTION;
PRAGMA EXCEPTION_INIT(arg1,arg2);
DECLARE
a NUMBER:=&a;
b NUMBER:=&b;
c NUMBER;
ZD EXCEPTION;
PRAGMA EXCEPTION_INIT(ZD,-01476);
BEGIN
c:=a/b;
DBMS_OUTPUT.PUT_LINE('QUOTIENT IS.....'||c);
40
EXCEPTION
WHEN ZD THEN
END;
CURSORS
Oracle provides a memory to process queries and that memory is called PRIVATE sql area.
1. Implicit cursors : These cursors will create memory automatically to process single row queries.
Oracle allocates memory, populates the data into that memory, and deallocates that memory when the
task is completed. It also contains the predefined attributes in that memory to perform various tasks (SQL
%FOUND,SQL%NOTFOUND,SQL%ROWCOUNT).
2. Explicit cursors: These cursors are created by a user to process multiple row queries. These cursors
are created based on 4 steps;
1. Declaration of cursor
2. Opening a cursor
1. Declaration of Cursor : A cursor variable is declared at declaration part of PL/SQL program associated
with SELECT query which is used at SQL. A cursor cant be associated with a SELECT....INTO query.
Any number of cursor variables can be declared associated with different queries.
syntax:
2. Opening a cursor : When a cursor gets opened, it executes the query which is associated to it and
makes the data available in that cursor.
syntax:
OPEN cursor_var[(list_of_args)];
3. Fetching the data from a cursor: Data can be extracted from a cursor variable w.r.to 1 row at a time into
buffer variables. It also transfers the control to the next row in a cursor making it ready for fetching.
syntax:
syntax:
CLOSE cursor_var;
CURSOR ATTRIBUTES:
1. %FOUND : It returns boolean value i.e. returns true if it points to a row else returns with false.
2. %NOTFOUND : It returns boolean value i.e. returns true if it does not point to a row else returns with
false.
3. %ISOPEN : It returns true if the cursor is opened else returns with false.
note: these attributes should be preceeded by cursor variable when they are used in PL/SQL program.
1. Write a program to create explicit cursor which will access multiple rows from emp table?
DECLARE
en emp.ename%TYPE;
pay emp.sal%TYPE;
dno emp.deptno%TYPE;
42
BEGIN
OPEN c1;
LOOP
END LOOP;
CLOSE c1;
END;
2. Write a program to create explicit cursor which supports to retrieve a required record from emp
table?
DECLARE
eno emp.empno%TYPE:=&eno;
a emp.empno%TYPE;
b emp.ename%TYPE;
c emp.sal%TYPE;
d emp.deptno%TYPE;
BEGIN
OPEN c1;
LOOP
43
IF a=eno THEN
END IF;
END LOOP;
CLOSE c1;
END;
3. Write a program to create explicit cursor which supports to store all the records of emp table
and calculates for the increment of salary on deptno thru buffer variables for a required employee
number.
DECLARE
eno emp.empno%TYPE:=&eno;
a emp.empno%TYPE;
b emp.ename%TYPE;
c emp.sal%TYPE;
d emp.deptno%TYPE;
BEGIN
OPEN c1;
44
LOOP
IF a=eno THEN
DBMS_OUTPUT.PUT_LINE('BEFORE INCREMENT');
c:=CASE d
END;
DBMS_OUTPUT.PUT_LINE('AFTER INCREMENT');
END IF;
END LOOP;
CLOSE c1;
END;
4. Write a program to create explicit cursor of all the records from emp table/ calculate the
increment of salary of all the employees based on categories of deptno with different percentages
thru buffer variables?
45
DECLARE
a emp.empno%TYPE;
b emp.ename%TYPE;
c emp.sal%TYPE;
d emp.deptno%TYPE;
i NUMBER;
BEGIN
OPEN c1;
LOOP
i:=CASE d
END;
END LOOP;
CLOSE c1;
END;
46
5. Write a program to create explicit cursor which will allow a user to retrieve the records of 20
dept?
DECLARE
a emp.empno%TYPE;
b emp.ename%TYPE;
c emp.sal%TYPE;
d emp.deptno%TYPE;
BEGIN
OPEN c1;
LOOP
END LOOP;
CLOSE c1;
END;
6. Write a program to create explicit cursor that retrieves all the records from emp table and
handle necessary exceptions related to cursors?
DECLARE
47
a emp.empno%TYPE;
b emp.ename%TYPE;
c emp.sal%TYPE;
d emp.deptno%TYPE;
e BOOLEAN;
BEGIN
OPEN c1;
e:=c1%ISOPEN;
IF e=TRUE THEN
DBMS_OUTPUT.PUT_LINE('CURSOR IS OPENED');
END IF;
LOOP
END LOOP;
CLOSE c1;
EXCEPTION
END;
48
PARAMETERISED CURSOR :
At this cursor it will allow a user to pass the data extracted from 1 cursor to the other cursor thru
arguments.
Parameter specification is provided at Declaration of cursor and when the cursor gets opened.
example:
Department..........................10
EMPNO ENAME
Department..........................20
EMPNO ENAME
Department..........................30
EMPNO ENAME
DECLARE
eno emp.empno%TYPE;
en emp.ename%TYPE;
dno emp.deptno%TYPE;
BEGIN
OPEN c1;
LOOP
49
DBMS_OUTPUT.PUT_LINE('Department...................'||dno);
DBMS_OUTPUT.PUT_LINE('EMPNO'||' '||'ENAME');
OPEN c2(dno);
LOOP
DBMS_OUTPUT.PUT_LINE(eno||' '||en);
END LOOP;
CLOSE c2;
END LOOP;
CLOSE c1;
END;
Data which is available in Cursor can be accessed using FOR looping construct, which does not
require opening of cursor, fetching the data from a cursor and closing a cursor.
For loop variable by default gets declared with a composite datatype i.e. %ROWTYPE. To access
the data of a cursor we refer to the columns of a table preceeded by cursor variable.
Syntax:
LOOP
statements;
END LOOP;
50
EXAMPLE:
DECLARE
BEGIN
FOR x IN c1
LOOP
END LOOP;
END;
REFERENCE CURSORS
A variable which is created based on such a datatype is generally called Cursor variable.
The primary Advantage of using cursor variables is to pass the result sets to different sub programs like
procedures,functions,packages etc.
Syntax:
EXAMPLE:
DECLARE
c_emp r_cursor;
en emp.ename%TYPE;
51
pay emp.sal%TYPE;
dno dept.deptno%TYPE;
dn dept.dname%TYPE;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(en||' '||pay);
END LOOP;
LOOP
DBMS_OUTPUT.PUT_LINE(dno||' '||dn);
END LOOP;
CLOSE c_emp;
END;
DECLARE
52
c_emp r_cursor;
erec emp%ROWTYPE;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE(erec.ename||' '||erec.sal);
END LOOP;
CLOSE c_emp;
END;
SUB PROGRAMS
1. Stored procedures
2. Stored Functions
3. Stored Packages
4. Triggers
Advantages of Subprograms:
2. Reusability.
53
STORED PROCEDURES:
Procedure is a self contained or predefined program which does not return any value.
Procedure are created as a stored block database object permanently in a database server.
Procedure can be provided with input arguments and can take some values from procedure after
its execution thru output arguments into calling program.
1. IN : By default arguments at procedure is set with IN mode, which will act like giving input to the
procedure. The arguments set with IN mode cant be modified. IN mode arguments will act like CALL BY
VALUE.
2. OUT : If arguments are set with OUT mode, it works for CALL BY REFERENCE. Any changes made to
the OUT arguments will automatically reflect into the Main program variables.
Syntax:
IS/AS
[local declaration;]
BEGIN
statement 1;
statement 2;
54
.......
statement n;
[EXCEPTION
exception handlers;]
END;
When the procedure is being created for 1st time then REPLACE option is not required, but when the
same procedure requires any changes and the same object is to be created again then we REPLACE the
procedure.
EXECUTION OF PROCEDURE:
EXEC proc_name(list_of_args)
proc_name(list_of_args);
EXAMPLES:
2 IS
3 c NUMBER;
4 BEGIN
5 c:=a+b;
6 DBMS_OUTPUT.PUT_LINE('SUM IS......'||c);
55
7 END;
8 /
Procedure created.
SUM IS......47
SUM IS......1143
SQL> ED PRO1
DECLARE
x NUMBER:=&x;
y NUMBER:=&y;
BEGIN
add_no(x,y);
END;
SQL> @PRO1
2. Create a procedure called display that provides the output using output statement of PL/SQL
program?
56
2 IS
3 BEGIN
4 DBMS_OUTPUT.PUT_LINE(a);
5 END;
6 /
Procedure created.
3. Create a procedure that takes 2 input arguments and return a value using output argument.
IS
BEGIN
c:=a+b;
END;
SQL> ED PRO2
DECLARE
x NUMBER:=&x;
y NUMBER:=&y;
z NUMBER;
BEGIN
sum_nos(x,y,z);
display('Sum Is......'||z);
display('Thanx');
57
END;
SQL> @PRO2
4. Create a procedure that takes 2 values as input and provides the quotient of 2 values? Handle
the exception if required?
IS
c NUMBER;
BEGIN
c:=a/b;
DISPLAY('QUOTIENT IS......'||c);
EXCEPTION
END;
5. Create a procedure that takes empno as input and displays ename,job,sal,deptno of that
employee?Handle necessary Exceptions?
2 IS
3 en emp.ename%TYPE;
58
4 des emp.job%TYPE;
5 pay emp.sal%TYPE;
6 dno emp.deptno%TYPE;
7 BEGIN
10 EXCEPTION
16 DISPLAY('MEM INSUFFICIENT');
17 END;
18 /
Procedure created.
NO ROW IS SELECTED
59
STORED FUNCTIONS
OR
Function can be defined as,"Self contained program, which returns maximum of 1 value".
Function is also created as stored block database object permanently in a database server.
Syntax:
RETURN data_type
IS
[local declaration;]
BEGIN
statement 1;
statement 2;
......
statement n;
RETURN var/val;
END;
60
var:=func_name(list_of_args);
examples:
create a function that takes 2 values as arguments and returns mutiplication of those values?
2 RETURN NUMBER
3 IS
4 c NUMBER;
5 BEGIN
6 c:=a*b;
7 RETURN c;
8 END;
9 /
Function created.
MUL_NOS(12,12)
--------------
144
SQL> ED PRO3
DECLARE
x NUMBER:=&x;
61
y NUMBER:=&y;
z NUMBER;
BEGIN
z:=MUL_NOS(x,y);
DISPLAY('PRODUCT IS........'||z);
END;
SQL> @PRO3
2 RETURN VARCHAR2
3 IS
4 en emp.ename%TYPE;
5 BEGIN
7 RETURN en;
8 END;
9 /
Function created.
2 FROM dual;
FIND_EMP(7788)
62
------------------------------------------------------------------
SCOTT
Create a function that takes n value as argument and returns Factorial of a given number?
Create a function that takes n value as argument and returns Reverse of a given number?
Create a function that takes n value as argument and check whether a given number is armstrong or not?
STORED PACKAGES
1. Package Specification:
Syntax:
IS
BEGIN
PROCEDURE proc_name1(list_of_args);
PROCEDURE proc_name2(list_of_args);
...................
63
...................
...................
END;
At package body respective definitions to procedures and functions are enclosed. A keyword
called BODY is used to create package definition.
Syntax:
IS
PROCEDURE proc_name1(list_of_args)
IS
[ local declaration; ]
BEGIN
statements;
[EXCEPTION
exception handlers;]
END;
......................
FUNCTION func_name1(list_of_args)
RETURN data_type
64
IS
[ local declaration; ]
BEGIN
statements;
RETURN var/val;
END;
......................
END;
To execute procedures:
EXEC pack_name.proc_name1(list_of_args)
To execute functions:
EXAMPLE:
2 IS
6 END;
7 /
65
Package created.
2 IS
4 IS
5 c NUMBER;
6 BEGIN
7 c:=a/b;
8 DISPLAY('QUOTIENT IS.....'||c);
9 EXCEPTION
12 END;
14 RETURN NUMBER
15 IS
16 c NUMBER;
17 BEGIN
18 c:=a*b;
19 RETURN c;
20 END;
21 END;
66
22 /
QUOTIENT IS.....2.5
TEST_PACK.MUL_NOS(12,12)
------------------------
144
DECLARE
dno dept.deptno%TYPE;
dn dept.dname%TYPE;
l dept.loc%TYPE;
BEGIN
OPEN test_pack.c1;
LOOP
67
END LOOP;
CLOSE test_pack.c1;
END;
1. USER_OBJECTS : This predefined table provides the information about different objects like tables,
views, Procedures, Functions, Packages etc.
2. USER_SOURCE : This predefined table provides the information about the code which is written for
different stored block objects.
GRANT:
EXAMPLE:
CONN SYSTEM/MANAGER
68
CONN SCOTT/TIGER
CONN SHAREEF/AHMED
EXEC SCOTT.SRCH_EMP(7788)
TO DROP PROCEDURES:
TO DROP FUNCTIONS:
TO DROP PACKAGES:
To drop a package it is essential that first package body should be dropped and then the package.
EXAMPLE:
69
In order to view the errors of the other stored block objects, it is essential that object type should be
mentioned followed by object name.
SHOW ERRORS
TRIGGERS
Trigger is defined as "Stored PL/SQL program unit, which is associated to a specific table".
Triggers are executed (fired) automatically whenever invalid operations are performed over a
table.
TYPES OF TRIGGERS:
1. DML Triggers : These triggers are fired BEFORE / AFTER the execution of DML commands like
INSERT, UPDATE, DELETE.
2. DDL Triggers : These triggers are executed BEFORE / AFTER the execution of DDL commands like
CREATE, ALTER, TRUNCATE, RENAME and DROP.
3. Database Triggers : These triggers are executed BEFORE / AFTER the database operations like LOG
ON/ LOG OFF/ SHUTDOWN / STARTUP of database.
ADVANTAGES OF TRIGGERS:
3. Triggers will take the backup of the data without the notice of operators.
4. Triggers will allow to create complex business logics that cant be provided by constraints.
70
1. DML Triggers : These triggers are executed BEFORE / AFTER the DML operations over a associated
table.
Syntax:
ON object_name
[ WHEN condition ]
[ DECLARE
declaration part; ]
BEGIN
Trigger Constraint
Trigger Action;
END;
EXECUTION OF TRIGGERS:
2. Row Level Trigger : These triggers are fired over each row that gets match with trigger constraint. If a
trigger is enclosed with option
From the above 2 types of triggers a table can be associated with maximum of 12 triggers.
I. STATEMENT LEVEL
71
1. BEFORE
i. INSERT
ii. UPDATE
iii. DELETE
2. AFTER
i. INSERT
ii. UPDATE
iii. DELETE
1. BEFORE
i. INSERT
ii. UPDATE
iii. DELETE
2. AFTER
i. INSERT
ii. UPDATE
iii. DELETE
NOTE:
2. Difference between trigger and constraint is, "constraint is associated to a column and trigger is fired
towards whole table".
3. Triggers takes the backup of data using bind variables :OLD and :NEW
While Inserting:
72
While Updating:
While Deleting:
4. Error is provided when invalid operation is performed over a trigger associated table, using a
predefined procedure called RAISE_APPLICATION_ERROR(arg1,arg2);
arg1 is user defired error number, which should be in a range of -20000 and -20999
arg2 is user defined error message, which can be of min 1 byte and max of 2048 bytes.
1. Create a statement level trigger for INSERT triggering event on EMP table where trigger should be
fired if the operation is performed on emp table other than working days.
3 BEGIN
4 IF RTRIM(TO_CHAR(SYSDATE,'DAY'))='SUNDAY' THEN
6 END IF;
7 END;
73
8 /
Trigger created.
2. Create a statement level trigger for INSERT triggering even on EMP table where trigger should be fired
if the operation is perfomred before 10am and after 17pm?
3 BEGIN
6 END IF;
7 END;
8 /
Trigger created.
3. Create a row level trigger for UPDATE triggering event on emp table which makes a backup of updated
and previous data into a new table.
EMPB
4 BEGIN
74
7 END;
8 /
Trigger created.
4. Create a row level trigger for UPDATE triggering event on emp table which makes the modified data in
a same table based on condition.
i.e. if modified data is more than the existing data then salary should be updated else trigger should be
fired and should retain the old salary.
4 BEGIN
5 IF :NEW.SAL<:OLD.SAL THEN
6 :NEW.SAL:=:OLD.SAL;
8 END IF;
9 END;
10 /
Trigger created
5. Create a row level trigger for DELETE triggering event on emp table where a row deleted from dept
table, related to that data all the records should be deleted from emp table?
4 BEGIN
7 END;
8 /
Trigger created.
INSERTING
UPDATING
DELETING
These attributes will return boolean value. if related operation is performed it returns TRUE else
returns with false.
DML_EVNTS
EVNT_NAME DAT
3 ON EMP
4 DECLARE
5 tn VARCHAR2(10);
6 BEGIN
76
7 IF INSERTING THEN
8 tn:='INSERT';
10 tn:='UPDATE';
12 tn:='DELETE';
13 END IF;
15 END;
16 /
Trigger created.
2. DDL TRIGGERS : These triggers are executed BEFORE / AFTER the DDL operation is performed
over a trigger associated table. It includes CREATE,ALTER, TRUNCATE, RENAME,DROP.
Syntax:
ON SCHEMA
BEGIN
Trigger Constraint
Trigger Action;
END;
77
ORA_DICT_OBJ_NAME : This attribute will return object name on which DDL operation is being
performed.
ORA_DICT_OBJ_TYPE : This attribute will return object type on which DDL operation is being performed.
BEGIN
IF ORA_DICT_OBJ_NAME='EMP' THEN
END IF;
END;
NOTE:
IF ORA_DICT_OBJ_TYPE='TABLE' THEN
END IF;
IF ORA_DICT_OBJ_TYPE='OBJECT' THEN
END IF;
The triggers which are created can be disabled and back can be enabled using ALTER
TRIGGER command.
78
SYNTAX:
To disable or enable all the triggers which are created on a table, it is essential that ALTER
TABLE command is used.
Syntax:
SYNTAX:
EXAMPLE:
USER_TRIGGERS: This predefined table will provide the information about the triggers like
trigger_name, triggering_event, table_name etc.
79