0% found this document useful (0 votes)
305 views

PL/SQL: by Lohit Mitra

PL/SQL is a programming technique used to manipulate Oracle databases. It uses blocks like DECLARE, BEGIN, and EXCEPTION similar to other block-structured languages. PL/SQL allows users to declare variables and their data types, write SQL statements, and handle exceptions. Examples demonstrate how to display employee data using PL/SQL and scalar and composite datatypes.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
305 views

PL/SQL: by Lohit Mitra

PL/SQL is a programming technique used to manipulate Oracle databases. It uses blocks like DECLARE, BEGIN, and EXCEPTION similar to other block-structured languages. PL/SQL allows users to declare variables and their data types, write SQL statements, and handle exceptions. Examples demonstrate how to display employee data using PL/SQL and scalar and composite datatypes.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

PL/SQL

BY LOHIT MITRA

SYSOFT TECHNOLOGY
AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

✓ PL/SQL is a programmatic approach to manipulate ORACLE database.


✓ Though PL/SQL is pronounced as language but it is not a language typically, rather than a program
technique to manipulate ORACLE database programmatically using SQL commands.
✓ To design a program using a specific language a language provides 4 different blocks i.e.
1. DECLARE
2. INPUT
3. PROCESS
4. OUTPUT
✓ In some programming languages, above blocks are physical in nature and identified by block names.
✓ These types of languages are categorized as BLOCK STRUCTURE LANGUAGE.
EX: COBOL
✓ But in some programming languages above blocks are logical in nature. Only user has to follow the
rules. These types of languages are categorised as UNBLOCKED STRUCTURE LANGUAGE.
EX: C, C++, JAVA etc.
✓ PL/SQL is an example of BLOCKED STRUCTURE PROGRAM TECHNIQUE which provides several
blocks to perform programming.
✓ EX:

DECLARE OPTIONAL

BEGIN COMPULSARY

(EXCEPTION) OPTIONAL

END; COMPULSARY

1. DECLARE: This block is responsible for declaration of identifiers (variables), types, cursors and
arrays to be used in PL/SQL. This block is optional in nature.
2. BEGIN/END: This block is responsible for input, process, output in PL/SQL. PL/SQL starts its
program execution from the BEGIN block and ends with END. This block is mandatory in nature.
3. EXCEPTION: This block is responsible for exception handling in PL/SQL. Whenever an exception
occurs during runtime system control will move to exception block handles thee exception and exits
out of the program normally. This block is optional in nature.

1|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

DATATYPES IN PL/SQL
✓ To design a program using a specific language the minimum requirement is a variable and a
variable’s minimum requirement is a datatype.
✓ PL/SQL provides two different types of data:
1. SCALAR DATATYPE
2. COMPOSITE DATATYPE
1. SCALAR DATATYPE:
✓ It is a datatype which can store one value at one point of time in form of one variable.
✓ Examples of scalar variables are:
a. CHAR
b. VARCHAR
c. NUMBER
d. DATE
e. BOOLEAN
✓ Apart from above datatypes PL/SQL provides a scalar attribute that is %TYPE.
2. COMPOSITE DATATYPE:
✓ Whereas composite datatype is a datatype which can store multiple values at one point of
time in form of one variable.
✓ Example of composite datatype is USER DEFINED DATATYPE or STRUCTURE or TYPE
DECLARATION.
✓ Apart from above composite datatypes PL/SQL provides a composite attribute called
%ROWTYPE.

SYNTAX TO DECLARE A VARIABLE:


DECLARE
V_NAME DATATYPE (SIZE)
V_NAME DATATYPE (SIZE) : = [ VALUE ] ;
Ex:

i number(4) : = 200;

In PL/SQL each statement is terminated by a semicolon ( ; ) and the assignment operator is : = whereas
the comparison operator is =.
STANDARD OUTPUT METHOD IN PL/SQL:
✓ PL/SQL provides a standard output method to display output in client machine and the method is:

BEGIN
dbms_output . put_line ( );

NOTE: put_line ( ) is a such type of method which is not going to display output in client machine until a
related SQL*PLUS command is written and the command is :

SET SERVEROUTPUT ON

2|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

The default behaviour of above command is OFF and this command can either be written at the top of
the program or at SQL prompt.

SQL STATEMENTS TO BE USED IN PL/SQL:


✓ Though PL/SQL is treated as the extended version of SQL, it can only use 3 sub-languages of SQL i.e.
DQL, DML, TCL.
✓ DDL and DCL commands are not allowed in PL/SQL.

SYNTAX OF ‘SELECT’ IN PL/SQL:


SELECT COL1, COL2, COL3, …………….. n
INTO V1, V2, V3, ………………………..n SELECTION
FROM TAB_NAME
WHERE <CONDITION>

Dbms_output.put_line (V1);
Dbms_output.put_line (V2);
Dbms_output.put_line (V3); PROJECTION
…………………………………
…………………………………
Dbms_output.put_line (Vn);

TYPES OF PL/SQL PROGRAMS:


✓ In PL/SQL user can design two types of programme i.e.
1. ANNONYMOUS BLOCK
2. SUB-PROGRAMME
✓ The primary jobs of above program are same i.e. to manipulate the database programmatically but
they are divided into two different categories depending on their security, execution and
mechanism.
1. ANNONYMOUS BLOCK:
✓ Anonymous block is a type of program whose program code is stored in the client in form of .sql
file or script file.
✓ Each time the program is executed it will move to the server, the server will compile the
program, execute it and return the output to the client which leads to the following
disadvantages:
a. Slower processing
b. Less program security
c. Makes network traffic busy
✓ By eliminating the loopholes of anonymous block a new type of program is introduced known as
SUB-PROGRAM.
2. SUB-PROGRAMME:
✓ Sub-programme is a type of program whose program code is stored inside the database server in
form of objects.

3|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

✓ Each time a request is made from the client and the program is executed inside the server and
output is returned back to the client which leads to the following advantages.:
a. Faster processing
b. Empower program security
c. Modularity
d. Robust
Example of ANONYMOUS PROGRAM:

The file will be saved in the following directory:

To run the file:

To start an ANONYMOUS PROGRAM, do the following:

4|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Output –

Q. Design a PL/SQL programme which will display employee no, employee name, salary, job, hire date of a
specific employee.
Ans.
set serveroutput on
set verify off
cl scr

DECLARE
vempno number(4);
vname varchar2(10);
vsal number(7,2);
vjob varchar2(10);
vdjoin date;
BEGIN
select empno, ename, sal, job, hiredate
into vempno, vname, vsal, vjob, vdjoin
from emp
where ename = upper('&name');

dbms_output.put_line('EMPLOYEE NO. : '|| vempno);


dbms_output.put_line('EMPLOYEE NAME : '|| vname);
dbms_output.put_line('SALARY : '|| vsal);
dbms_output.put_line('JOB : '|| vjob);
dbms_output.put_line('JOIN DATE : '|| vdjoin);
END;
/
OUTPUT –

✓ Above example is an example of SCALAR DATATYPE which can store one value at one point of
time.

5|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Working with SCALAR ATTRIBUTE:


✓ %TYPE is a scalar attribute responsible to declare a variable a variable as a table’s column type or
another variable types.
✓ Advantage of SCALAR ATTRIBUTE is it makes program development flexible.
✓ Taking the help of above example, we can use the scalar attribute in our program as below:
DECLARE
vempno emp.empno%type;
eno vempno%type;
vname emp.ename%type;
vsal emp.sal%type;
vjob emp.job%type;
vdjoin emp.hiredate%type;
✓ Here datatype size = type of column
✓ Above example shows vempno is a variable which is type of the table’s column i.e. EMP table’s
EMPNO type. Whereas eno is a variable which is another variable type i.e. vempno type.

Working with COMPOSITE ATTRIBUTE:


✓ %ROWTYPE is a composite attribute responsible to declare a variable as a table structure type.
✓ Advantages of %ROWTYPE is it reduces the program code by declaring limited number of variables.
✓ For example:
DECLARE
rec emp%rowtype;
rec2 emp%rowtype;

BEGIN
select *
into rec
from emp
where ename = upper('&name');

select *
into rec2
from emp
where ename = upper('&name');

dbms_output.put_line('EMPLOYEE NO. : '|| rec.empno);


dbms_output.put_line('EMPLOYEE NAME : '|| rec.ename);
dbms_output.put_line('SALARY : '|| rec.sal);
dbms_output.put_line('JOB : '|| rec.job);
dbms_output.put_line('JOIN DATE : '|| rec.hiredate);

dbms_output.put_line('EMPLOYEE NO. : '|| rec2.empno);


dbms_output.put_line('EMPLOYEE NAME : '|| rec2.ename);
dbms_output.put_line('SALARY : '|| rec2.sal);
dbms_output.put_line('JOB : '|| rec2.job);
dbms_output.put_line('JOIN DATE : '|| rec2.hiredate);
END; /

6|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

✓ Above example shows rec and rec2 are 2 variables which are table structure type which leads to
less amount of coding.

Working with COMPOSITE DATATYPE:


✓ Though the advantage of %ROWTYPE is to reduce the coding of the program it also supports
following disadvantages
o Use of unnecessary memory space
o Unable to store multiple table’s data
✓ By eradicating the loopholes of %ROWTYPE user can design its own structure known as TYPE
DECLARATION.

SYNTAX TO DECLARE USER DEFINED TYPE:


DECLARE

TYPE < T_NAME > IS RECORD


(V_NAME DATATYPE (SIZE)
V_NAME DATATYPE (SIZE)
……………………………………..
……………………………………. n ) ;
SYNTAX TO DECLARE A VARIABLE OF STRUCTURE TYPE:
DECLARE
V_NAME < T_NAME >;
✓ Once a structure is created in PL/SQL user can declare different variables of the structure type.

Q. Design a PL/SQL programme which will display employee no, employee name, salary, job, hire date,
grade, department name, location of a specific employee.
Ans.
set serveroutput on
set verify off
cl scr

DECLARE
type mytype is record
(vempno emp.empno%type,
vname emp.ename%type,
vsal emp.sal%type,
vjob emp.job%type, STRUCTURE
vhiredate emp.hiredate%type,
vgrade salgrade.grade%type,
vdname dept.dname%type,
vloc dept.loc%type);

7|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

rec1 mytype;
rec2 mytype; VARIABLE CONTAINING STRUCTURE
rec3 mytype; (BECAUSE STRUCTURE CAN’T BE DIRECTLY USED IN THE PROGRAM)

BEGIN
select empno, ename, sal, job, hiredate, grade, dname, loc
into rec1
from emp, dept, salgrade
where sal between losal and hisal
and emp.deptno = dept.deptno
and ename = upper('&name');

dbms_output.put_line('EMPLOYEE NO. : '|| rec1.vempno);


dbms_output.put_line('EMPLOYEE NAME : '|| rec1.vname);
dbms_output.put_line('SALARY : '|| rec1.vsal);
dbms_output.put_line('JOB : '|| rec1.vjob);
dbms_output.put_line('JOIN DATE : '|| rec1.vhiredate);
dbms_output.put_line('GRADE : '|| rec1.vgrade);
dbms_output.put_line('DEPT. NAME : '|| rec1.vdname);
dbms_output.put_line('LOCATION : '|| rec1.vloc);

END;
/
OUTPUT –

✓ Above example shows once a structure is created user can declare several number of variables of
that structure.

ANOTHER WAY OF THE ABOVE QUESTION:


DECLARE

vempno emp.empno%type;
vname emp.ename%type;
vsal emp.sal%type;
vjob emp.job%type;

8|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

vhiredate emp.hiredate%type;
vgrade salgrade.grade%type;
vdname dept.dname%type;
vloc dept.loc%type;

BEGIN
select empno, ename, sal, job, hiredate, grade, dname, loc
into vempno, vname, vsal, vjob, vhiredate, vgrade, vdname, vloc
from emp, dept, salgrade
where sal between losal and hisal
and emp.deptno = dept.deptno
and ename = upper('&name');

dbms_output.put_line('EMPLOYEE NO. : '|| vempno);


dbms_output.put_line('EMPLOYEE NAME : '|| vname);
dbms_output.put_line('SALARY : '|| vsal);
dbms_output.put_line('JOB : '|| vjob);
dbms_output.put_line('JOIN DATE : '|| vhiredate);
dbms_output.put_line('GRADE : '|| vgrade);
dbms_output.put_line('DEPT. NAME : '|| vdname);
dbms_output.put_line('LOCATION : '|| vloc);

END;
/

WORKING WITH CONTROL STRUCTURE:


✓ Control structure is a block of executable statements which will perform a task once or number of
times until a condition is satisfied.
✓ In other words control structures are basically required for condition wise tasks.
✓ PL/SQL provide following control structures
1. IF …….. ELSE ……….. END IF
2. BASIC LOOP (Like DO WHILE)
3. FOR LOOP
4. WHILE LOOP

SYNTAX OF SIMPLE IF (one condition one job):


IF (< CONDITION>) THEN
STATEMENTS;
ELSE
STATEMENTS;
END IF;

9|Page SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

SYNTAX OF NESTED IF (multiple condition one job):


IF (< CONDITION >) THEN
STATEMENTS;
ELSIF (< CONDITION >) THEN
STATEMENTS;
ELSIF (< CONDITION >) THEN
STATEMENTS;
ELSE
STATEMENTS
END IF;

SYNTAX OF SWITCH CASE:


CASE
WHEN (< CONDITION >) THEN
STATEMENTS;
WHEN (< CONDITION >) THEN
STATEMENTS;
ELSE
STATEMENTS;
END CASE;

10 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Q. Design a PL/SQL program which will display employee number, name, salary, job of a specific employee
and calculate ta, da respectively 10% and 12% of that employee; at the same point of time insert the
record in a specific table depending on the condition that if the employee is a manager then record goes to
the manager table, if salesman then record goes to the salesman table, if analyst then record goes to the
analyst table and if any other then record goes to the other table.
Ans.
set serveroutput on
set verify off
cl scr

DECLARE
type str is record
( vempno emp.empno%type,
vename emp.ename%type,
vsal emp.sal%type,
vjob emp.job%type );

rec str;

ta emp.sal%type;
da ta%type;
BEGIN
select empno, ename, sal, job into rec from emp where
ename = upper('&ename');
ta := rec.vsal*.1;
da := rec.vsal*.12;

dbms_output.put_line('EMPLOYEE NUMBER: '||rec.vempno);


dbms_output.put_line('EMPLOYEE NAME: '||rec.vename);
dbms_output.put_line('EMPLOYEE SALARY: '||rec.vsal);
dbms_output.put_line('JOB: '||rec.vjob);
dbms_output.put_line('TA: '||ta);
dbms_output.put_line('DA: '||da);

if (rec.vjob = 'MANAGER') then


insert into manager_tab
values (rec.vempno, rec.vename, rec.vsal, rec.vjob, ta, da);
elsif (rec.vjob = 'SALESMAN') then
insert into salesman_tab
values (rec.vempno, rec.vename, rec.vsal, rec.vjob, ta, da);
elsif (rec.vjob = 'ANALYST') then
insert into analyst_tab
values (rec.vempno, rec.vename, rec.vsal, rec.vjob, ta, da);
else
insert into other_tab
values (rec.vempno, rec.vename, rec.vsal, rec.vjob, ta, da);
end if;
END; /

11 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

✓ The output of the above program is :

12 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Working with LOOP statements:


✓ PL/SQL provides 3 different type of looping to perform a task multiple number of times and those
are:
1. BASIC LOOP (do- while {false based})
2. WHILE LOOP (true based)
3. FOR LOOP

1. BASIC LOOP / WHILE LOOP:


✓ Basic loop is a type of looping which is identical with do-while in ‘C’ ; that means in do-while, the
statement is executed first and then it checks the condition.

SYNTAX:
LOOP
statement;
statement;
EXIT [WHEN <CONDITION>];
END LOOP;

13 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

2. WHILE LOOP:
✓ In while loop condition is checked first then it executes the statement.

SYNTAX:
WHILE (<CONDITION>) LOOP
statement;
statement;
statement;
END LOOP;
EX: do-while loop:
set serveroutput on
set verify off
cl scr

DECLARE
i number(4) := 1;
BEGIN
LOOP
dbms_output.put_line(i);
i := i+1;
exit when i>10;
END LOOP;
END;
/

EX: while loop:


set serveroutput on
set verify off
cl scr

DECLARE
i number(4) := 1;
BEGIN
while (i <= 10)

LOOP

dbms_output.put_line(i);
i := i+1;

END LOOP;
END;
/

14 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

✓ Basic loop executes at least once if the condition is false.


✓ But while loop will not execute once at least if the condition is false.

3. FOR LOOP:
✓ FOR loop is a type of looping where initialization, incrementation and condition checking is
automatically done by the system the formula given by the user.
✓ The advantage of for loop is it reduces program coding.
✓ PL/SQL for loop also supports inline declaration.
✓ In FOR loop by default increment is 1 and can’t be incremented to any number.

SYNTAX:
FOR <COUNTER> IN [ REVERSE ] LowerBound . . UpperBound
LOOP
statement;
statement;
statement;
END LOOP;

Ex: For Loop:

set serveroutput on
set verify off
cl scr

DECLARE
i number(4);
BEGIN
FOR i in reverse 1..20

LOOP

dbms_output.put_line(i);

END LOOP;
END;
/

NOTE: If declare block is removed then ‘i’ becomes inline.

15 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

ARRAYS IN PL/SQL
✓ Array is a concept or a technique through which user can store homogeneous types of data in a
contiguous memory location which share a common name.
✓ Each element in an array variable is identified by subscript or index starting from 1 to n.
✓ Advantage of array concept is it reduces program coding by declaring limited no. of variables.
✓ In PL/SQL arrays are basically an user defined ‘TYPE’. Thus, they can’t be used in the program
directly and a variable of array type is used in the program.
✓ In PL/SQL, array is broadly categorized into two different types i.e.
1. VARRAY (STATIC ARRAY)
2. NESTED TABLES (DYNAMIC ARRAY)
✓ VARRAY is a type of array whose subscript is always fixed whereas NESTED TABLE is a dynamic
array whose subscript can be dynamically changed.
✓ Ex: VARRAY:
set serveroutput on
set verify off
cl scr

DECLARE Can’t be used directly in program


type myary is VARRAY(5) of number;

x myary;
y myary;
Variables of array type
total number(5) := 0;
BEGIN
x := myary(10,20,30,40,50); Type casting

for i in 1 .. x.count Property of x (array variable)

LOOP
dbms_output.put_line(x(i));
total := total + x(i);

END LOOP;

dbms_output.put_line('======================');

dbms_output.put_line('TOTAL ='||total);

END;
/

16 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Output:

✓ Above example is an example of a static array which can allocate 5 subscripts.


✓ User can declare dynamic array in the following manner:
DECLARE
type myary is table of number;
x myary;
y myary;
total number(5) := 0;
BEGIN
x := myary(78,98,87,76,32,64,45,24,14,76);

for i in 1 .. x.count

LOOP
dbms_output.put_line(x(i));
total := total + x(i);

END LOOP;

dbms_output.put_line('======================');
dbms_output.put_line('TOTAL ='||total);

END;
/

✓ Using above example user can store n number of values at run time.

17 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

: CURSOR :
✓ Whenever a PL/SQL programme is executed, the SQL statements issued from the PL/SQL
programme executed in their respective memory technically known as CURSOR.
✓ “Cursor is a private sequel area where a statement is stored as well as processed. And once the
processing is done the memory is destroyed.”
✓ NOTE: A cursor passes through 4 different stages i.e.
1. DECLARE: Declaration of the cursor means the memory will be created for the first time and
the statement (select/insert/update/delete) will be stored inside that.
2. OPEN: Opening of cursor means the statement available inside the memory will be executed
and the output will be kept inside the same memory.
3. FETCH: Fetching of cursor means the output available inside the memory will be transferred
one by one to their respective variable.
4. CLOSE: Once all the above jobs are done, the memory is going to be deallocated technically
known as closing of cursor.
✓ Types of cursors:
1. IMPLICIT CURSOR: A SQL (implicit) cursor is opened by the database to process each SQL
statement that is not associated with an explicit cursor. Implicit cursor is the type of job where all
above jobs i.e. declare, open, fetch, close are done automatically by the server. But the disadvantage
of implicit cursor is it can store maximum 1 record at one point of time for processing purpose.
2. EXPLICIT CURSOR: Whereas explicit cursor is a type of cursor where all above jobs are
explicitly done by the user but the advantage of explicit cursor is it can store multiple
records at one point of time for processing purpose.

CURSOR MECHANISM (DECLARE AND OPEN)

18 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

CURSOR MECHANISM (FETCH AND CLOSE)


✓ Above graphics shows the cursor creation and fetch and closing mechanism.

CURSOR ATTRIBUTES:
✓ To design cursor program oracle provides several cursor attributes namely:

a. %FOUND:
This attribute is responsible to check whether the record pointer is getting the record
from the cursor memory or not. It returns Boolean value.

b. %NOTFOUND:
This attribute is just opposite of %FOUND.

c. %ISOPEN:
This attribute is responsible to check programmatically whether cursor memory is
opened or not. It also returns Boolean type of values.

d. %ROWCOUNT:
This attribute is responsible to count the number of records fetched from the cursor.

✓ Above attributes are valueless without a cursor name. therefore, each and individual cursor is suffixed
with a cursor name.

NOTE: Each and individual cursor is identified by a name. In implicit cursor concept, name is by default
“SQL” whereas in explicit cursor concept, the name is given by the user and user can’t give an
explicit cursor name as “SQL”.

19 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

IMPLICIT CURSOR ATTRIBUTE EXPLICIT CURSOR ATTRIBUTE

SQL %FOUND C1 %FOUND

SQL %NOTFOUND C1 %NOTFOUND

SQL %ISOPEN C1 %ISOPEN

SQL %ROWCOUNT C1 %ROWCOUNT

TYPES OF EXPLICIT CURSORS:


✓ Explicit cursor is broadly categorized in two different types.
o SIMPLE / STATIC CURSOR
o ADVANCED / DYNAMIC CURSOR / CURSOR WITH PARAMETER
✓ User can write following cursor program according to the requirement
o Simple cursor using basic loop and for loop
o Advance cursor using basic loop and for loop
✓ No ‘while’ loop is allowed in cursor programming.

SYNTAX TO DECLARE A CURSOR:


DECLARE
CURSOR <C_NAME> IS <SELECT STATEMENT>;

SYNTAX TO OPEN A CURSOR:


BEGIN
OPEN <C_NAME>;

SYNTAX TO FETCH A CURSOR:


FETCH <C_NAME> INTO <Var_NAME>;
SYNTAX TO CLOSE A CURSOR:
CLOSE <C_NAME>;
END;
/

20 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

WORKING WITH SIMPLE CURSOR USING BASIC LOOP:


Q. Design a PL/SQL program which will display employee number, name, salary, job and hire date of those
employee whose job is MANAGER or SALESMAN.
Ans.
set serveroutput on
set verify off
cl scr

DECLARE
CURSOR c1 is
select empno, ename, sal, job, hiredate
from emp
where job in ('MANAGER','SALESMAN');
rec c1%rowtype;
BEGIN
OPEN c1;

LOOP
FETCH c1 into rec;
EXIT WHEN c1%notfound;

dbms_output.put_line('EMPLOYEE NAME: '||rec.ename);


dbms_output.put_line('EMPLOYEE NO.: '||rec.empno);
dbms_output.put_line('SALARY: '||rec.sal);
dbms_output.put_line('DATE OF JOINNING: '||rec.hiredate);
dbms_output.put_line('JOB:'||rec.job);
dbms_output.put_line('========================');
END LOOP;

dbms_output.put_line(c1%rowcount||'number of records fetched...');


CLOSE c1;

END;
/

21 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

OUTPUT:

(cursor program mechanism)


** BOF = Begin Of File and EOF = End Of File

22 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

NOTE: “Open” is a keyword which can perform two jobs.


1. Execute the statement and store the output inside the memory.
2. Set the pointer to the first record of the record set.
Whereas “FETCH” is a keyword which can perform 2 jobs
1. Fetch the current record into a variable and
2. Skip the pointer to the next record of the record set.
(Record set or result set is basically an output returned by query statement)

WORKING WITH SIMPLE CURSOR USING ‘FOR’ LOOP:


✓ Cursor ‘for’ loop is a type of cursor where declaration of cursor is explicitly done by the user but
opening, fetching and closing is implicitly done by the server which leads to less amount of coding.

SYNTAX:
DECLARE
CURSOR <C_NAME> IS < SELECT STATEMENT >;
BEGIN
FOR <V_NAME> IN <C_NAME> LOOP  OPEN + FETCH
END LOOP;  CLOSE
END;
/
✓ Cursor ‘for’ loop has been designed in such a manner, whenever ‘for’ loop encounters the cursor
for the first time, the cursor is automatically treated as opened.
✓ In such iteration, the cursor is going to be fetched and once ‘for’ loop encounters the end loop, the
cursor is treated as closed.
Q. Design a PL/SQL program which will display employee number, salary, job and hire date of those
employees whose job is manager, salesman or analyst. Along with that those records are going to be
inserted into a table by calculating ta, da respectively 10%, 12 % whose salary is greater than 2000.
Ans.
DECLARE
CURSOR c1 is
select empno, ename, sal, job, hiredate
from emp
where job in ('MANAGER','SALESMAN','ANALYST');
int number;
ta number;
da number;
total number;
rec c1%rowtype;

23 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

BEGIN
FOR rec in c1 LOOP
ta := rec.sal*.1;
da := rec.sal*.12;
total := ta+da+rec.sal;

dbms_output.put_line('Employee Number: '||rec.empno);


dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Hiredate: '||rec.hiredate);
dbms_output.put_line('Employee Job: '||rec.job);
dbms_output.put_line('Employee TA: '||ta);
dbms_output.put_line('Employee DA: '||da);
dbms_output.put_line('TOTAL SALARY: '||total);
dbms_output.put_line('=====================================');
int:=c1%rowcount;

IF (rec.sal>2000 and rec.job='MANAGER') THEN


insert into MANAGER_TAB
values(rec.empno, rec.ename, rec.sal,rec.job,ta,da,rec.hiredate,total);
commit;
dbms_output.put_line('row inserted...');
dbms_output.put_line('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@');

ELSIF (rec.sal>2000 and rec.job='ANALYST') THEN


insert into ANALYST_TAB
values(rec.empno, rec.ename, rec.sal, rec.job,ta,da,rec.hiredate,total);
commit;
dbms_output.put_line('row inserted...');
dbms_output.put_line('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@');

ELSIF (rec.sal>2000 and rec.job='SALESMAN') THEN


insert into SALESMAN_TAB
values(rec.empno, rec.ename, rec.sal, rec.job,ta,da,rec.hiredate,total);
commit;
dbms_output.put_line('row inserted...');
dbms_output.put_line('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@');

END IF;

END LOOP;

dbms_output.put_line(int||' rows fetched ....' );

END;
/

24 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

O/P-

WORKING WITH ADVANCE CURSOR/DYNAMIC CURSOR OR CURSOR


WITH PARAMETER (BASIC LOOP):
✓ Advance cursor is a type of cursor which will ask a value during runtime and once value is entered
cursor starts its execution.
✓ Advance cursor otherwise known as parameter wise cursor that means it will accept a value
through an argument.

SYNTAX:
DECLARE

CURSOR < C_NAME > ( ARG DATATYPE, …………… n ) IS

SELECT STATEMENT
WHERE COL_NAME = ARG;
BEGIN
OPEN < C_NAME > (VALUE / EXP);

25 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Q. Design a PL/SQL program which will display employee number, salary, job and hire date and department
number of a specific department.
Ans.
set serveroutput on
set verify off
cl scr

DECLARE
CURSOR c1(vdno number) is
select empno, ename, sal, job, hiredate, deptno
from emp
where deptno = vdno;
rec c1%rowtype;
BEGIN
OPEN c1(&deptno);

LOOP
FETCH c1 into rec;
EXIT WHEN c1%notfound;

dbms_output.put_line('Employee Number: '||rec.empno);


dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Hiredate: '||rec.hiredate);
dbms_output.put_line('Employee Job: '||rec.job);
dbms_output.put_line('Employee Department: '||rec.deptno);
dbms_output.put_line('=====================================');

END LOOP;

CLOSE c1;

END;
/

ADVANCE CURSOR USING ‘FOR’ LOOP:


DECLARE
CURSOR c1(vdno number) is
select empno, ename, sal, job, hiredate, deptno
from emp
where deptno = vdno;
rec c1%rowtype;

26 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

BEGIN

FOR rec in c1(&deptno)

LOOP
dbms_output.put_line('Employee Number: '||rec.empno);
dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Hiredate: '||rec.hiredate);
dbms_output.put_line('Employee Job: '||rec.job);
dbms_output.put_line('Employee Department: '||rec.deptno);
dbms_output.put_line('=====================================');
END LOOP;

END;
/
Q. Design a PL/SQL program which will display employee number, name, salary, job and hire date and
department number, location and grade of a specific Job type.
Ans.
set serveroutput on
set verify off
cl scr

DECLARE
CURSOR c1(vjob emp.job%type) is
select empno, ename, sal, job, hiredate, emp.deptno, loc, grade
from emp, dept, salgrade
where sal between losal and hisal
and emp.deptno = dept.deptno
and job = UPPER(vjob);

BEGIN

FOR rec in c1('&vjob')

LOOP
dbms_output.put_line('Employee Number: '||rec.empno);
dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Hiredate: '||rec.hiredate);

27 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

dbms_output.put_line('Employee Job: '||rec.job);


dbms_output.put_line('Employee Department Number: '||rec.deptno);
dbms_output.put_line('Employee Location: '||rec.deptno);
dbms_output.put_line('Salary grade: '||rec.grade);
dbms_output.put_line('=====================================');
END LOOP;

END;
/

O/P-

CURSOR

IMPLICIT CURSOR EXPLICIT CURSOR

ATTRIBUTES SIMPLE / STATIC CURSOR


%FOUND (BASIC LOOP & FOR LOOP)

%NOTFOUND

%ISOPEN
ADVANCED / DYNAMIC CURSOR /
%ROWCOUNT
CURSOR WITH PARAMETER
(BASIC LOOP & FOR LOOP)

28 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

SUBPROGRAM
✓ Subprogram is a type of program which is treated as the extended version of anonymous block.
✓ Basic advantages of subprogram is it resides inside the server in form of object which leads to
following advantages.
1. Faster execution
2. Program securing
3. Robust (sharable)
4. Modularity (one program calls another program)
✓ It is broadly categorized into two parts.
a. Stored Procedures
b. Stored Functions

PROCEDURES

SYNTAX TO CREATE A PROCEDURE:


CREATE [OR REPLACE] PROCEDURE <PRO_NAME> [ (ARG DATATYPE,....N) ]
IS/AS
VARIABLE DECLARATION;
TYPE DECLARATION;
ARRAY DECLARATION;
CURSOR DECLARATION;
BEGIN
STATEMENT;
STATEMENT;
STATEMENT;

END <PRO_NAME>;
/

29 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

NOTE:
• Anonymous programs are otherwise known as unnamed blocks as because anonymous programs
are identified by their file name whereas subprograms are otherwise known as named blocks
where each program is identified by a name.
• As because subprograms are named blocks one subprogram can call another which leads to
modularity.

Ex:
CREATE OR REPLACE PROCEDURE fsubprog
is
BEGIN
dbms_output.put_line('My first PROCEDURE PROGRAMME....');
END;
O/P –

✓ It is advisable to provide the procedure name same as the SQL file name.
✓ To run or call the procedure from sql*plus user can use ‘execute’ command.

CALLING A PROCEDURE FROM ANOTHER PROCEDURE


✓ To call a procedure from another procedure simply write the procedure name in caller’s BEGIN and
END blocks.
✓ Ex:
CREATE OR REPLACE PROCEDURE subprog1
IS

BEGIN
for i in 1..10 loop
fsubprog;
end loop;

END subprog1;
/

30 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

O/P –

Q. Design a procedure which will accept 2 different arguments then multiply and display.
Ans.
create or replace procedure fsubprog(i number, j number)
is
k number;
BEGIN
k:= i*j;
dbms_output.put_line(i ||' X ' ||j||'='||k);
END fsubprog;
/

O/P-

Q. Design a procedure which will accept job type as an argument and display employee number, name,
salary, job and hire date of the concern job type.

Ans.

create or replace procedure subprog(vjob varchar2)


is
cursor c1(sjob varchar2) is
select empno,ename,sal,job,hiredate
from emp where job=upper(sjob);

31 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

begin
for
rec in c1(vjob) loop
dbms_output.put_line('Employee No: '||rec.empno);
dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Job: '||rec.job);
dbms_output.put_line('Employee Date Join: '||rec.hiredate);
dbms_output.put_line('===================');
end loop;
end subprog;
/

O/P –

Q. Design a procedure which will accept department number and job type as arguments and display
employee number, name, salary, job, dept. name and location of the concern dept. and job type.

Ans.

create or replace procedure subprog(vjob varchar2, vdname varchar2)


is

cursor c1(cjob varchar2, cdname varchar2) is


select empno,ename,sal,job,dname,loc
from emp,dept
where emp.deptno=dept.deptno
and job=upper(cjob)
and dname=upper(cdname);

32 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

begin
for
rec in c1(vjob,vdname) loop
dbms_output.put_line('Employee No: '||rec.empno);
dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Job: '||rec.job);
dbms_output.put_line('Employee Department: '||rec.dname);
dbms_output.put_line('Department Location: '||rec.loc);
dbms_output.put_line('===================');
end loop;
end subprog;
/

O/P-

~ o ~

33 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

FUNCTIONS
SYNTAX TO CREATE A FUNCTION:
CREATE [OR REPLACE] FUNCTION <F_NAME> [ (ARG DATATYPE, ....N) ] RETURN <DATATYPE>
IS/AS
VARIABLE DEC;
TYPE DEC;
ARRAY DEC;
CURSOR DEC;
BEGIN
STATEMENT;
STATEMENT;
STATEMENT;

RETURN (VALUE|EXP);

Syntax to call a function:


V_Name : = F_Name ( P1, P2, …… n )
NOTE: Once a function is designed, it can either be called from another procedure, another function or
from an anonymous program. A function cannot be directly executed from the sql prompt.

Q. Design 3 different functions namely fta, fda and ftotal salary which will calculate TA, DA respectively in
10% and 12% and total salary. Call these functions from fsubprog procedure.
Ans.
CREATING FUNCTIONS: -
create or replace function fta(vsal number) return number
is
ta emp.sal%type;
begin
ta:=vsal*.1;

return (ta);
end fta;
/

create or replace function fda(vsal number) return number


is
da emp.sal%type;
begin
da:=vsal*.1;

return (da);

34 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

end fda;
/

create or replace function ftotalsal(vsal number,vta number,vda number) return


number
is
totalsal emp.sal%type;

begin
totalsal:=vsal+vta+vda;

return(totalsal);

end ftotalsal;
/

CREATING PROCEDURE AND CALLING FUNCTIONS: -


create or replace procedure fsubprog(vjob varchar2)
is
cursor mycur(sjob varchar2) is
select empno,ename,sal,job,hiredate from emp
where job=sjob;

ta number;
da number;

begin
for rec in mycur(vjob) loop
dbms_output.put_line('Employee No: '||rec.empno);
dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Job: '||rec.job);
dbms_output.put_line('Employee Hiredate: '||rec.hiredate);

ta := fta(rec.sal);
da := fda(rec.sal);

dbms_output.put_line('Ta: '||ta);
dbms_output.put_line('Da: '||da);
dbms_output.put_line('Total salary: '|| ftotalsal(rec.sal,ta,da));
dbms_output.put_line('=======================');
end loop;
end subprog2;
/

35 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

O/P –

NOTE: Once a stored function is created, the function can be used in query statement to accomplish a
specific job.

Ex:

~ O ~

36 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

PACKAGE
✓ Package is simply a container which contains procedures and functions to be used by one user or
several users.
✓ Advantage of package concept is it makes procedure and function execution faster.
✓ Package supports the concept of FUNCTION POINTER.
✓ If a procedure or function is called through its name then it is called by value.
✓ But if they are called through package name then it is called as called by reference.
✓ To keep a procedure or function within a package, user must design those procedure and function
within the package itself.
✓ Package has 2 different parts or blocks i.e.
1. Package specification: this block is a block where procedures and functions are to be
defined.
2. Package body: whereas package body block is a block where procedure and functions are to
be designed, specified in the specification block.
✓ Package never takes any argument nor return any value coz it is not an application but it is a set of
collection of applications.

SYNTAX OF PACKAGE SPECIFICATION:


CREATE [OR REPLACE] PACKAGE <P_NAME>
IS/AS
PROCEDURE < PRO_NAME > [ (ARG DATATYPE, ….... n ) ];
PROCEDURE < PRO_NAME > [ (ARG DATATYPE, .... n ) ];
..........................N;
FUNCTION < F_NAME > [ (ARG DATATYPE, ......n) ] RETURN < DATATYPE >;
FUNCTION < F_NAME > [ (ARG DATATYPE, ......n) ] RETURN < DATATYPE >;
..........................N;
END <P_NAME>;
/
SYNTAX OF PACKAGE BODY:
CREATE [OR REPLACE] PACKAGE BODY < P_NAME >
IS/AS
PROCEDURE < PRO_NAME > [(ARG DATATYPE, ..... n)]
IS/AS
VARIABLE DEC;
TYPE DEC;
CURSOR DEC;
ARRAY DEC;

37 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

BEGIN
STATEMENT;
STATEMENT;
STATEMENT;

END <PRO_NAME>;

FUNCTION < F_NAME > [(ARG DATATYPE, ..... n)] RETURN DATATYPE
IS/AS
VARIABLE DEC;
TYPE DEC;
CURSOR DEC;
ARRAY DEC;

BEGIN
STATEMENT;
STATEMENT;
STATEMENT;

RETURN < VALUE|EXP >;

END < F_NAME >;

..........................
.................
.........
END <P_NAME>;
/

38 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Q. Design a package which will have following procedure and functions.


1. “ourprogdisplay” is a procedure which will display simple message i.e. “First package program”
2. “ourprogins” is a procedure which will accept employee number, name, salary, job and insert into a
table called EMP_TAB.
3. “ourprogdno” is a function which will accept dno as an argument and display employee number, name,
sal, job of the concerned department.
Ans.
create or replace package mypack
is
procedure ourprogdisplay;
procedure ourprogins(vempno number,vname varchar2,vsal number,vjob
varchar2);
procedure ourprogdno(vdno number);
end mypack;
/

create or replace package body mypack


as
procedure ourprogdisplay
is

BEGIN
dbms_output.put_line('Our first package programme...');
END ourprogdisplay;

procedure ourprogins(vempno number,vname varchar2,vsal number,vjob


varchar2)
is

BEGIN
insert into employeetab
values(vempno,vname,vsal,vjob);

COMMIT;
END ourprogins;

procedure ourprogdno(vdno number)


is
CURSOR c1(sdno number) is
select empno,ename,sal,job,deptno
from emp where deptno=sdno;

BEGIN
FOR rec in c1(vdno) LOOP
dbms_output.put_line('Employee No: '||rec.empno);
dbms_output.put_line('Employee Name: '||rec.ename);
dbms_output.put_line('Employee Salary: '||rec.sal);
dbms_output.put_line('Employee Job: '||rec.job);
dbms_output.put_line('Employee Deptno: '||rec.deptno);
dbms_output.put_line('======================');
END LOOP;

39 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

END ourprogdno;
END mypack;
/

o/p –

40 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

METHOD OVERLOADING:
✓ As because ORACLE 11g is an object relational database its package supports the concept of
method overloading i.e. several methods are identified by a single name.
✓ System will identify the methods through no. of arguments, types of arguments and sequence of
arguments.
✓ For example in the above package program if we rename all the procedures to ourprog, still they
are going to work.
o ourprogdisplay  ourprog
o ourprogins  ourprog(vempno, vname, vsal,vjob)
o ourprogdno  ourprog(vdno)

NOTE: Package specification is an object which will move to client with addresses. In general, package
specification is a client side objects whereas package body is a server side object.

To delete a package:
DROP PACKAGE <PACKAGE_NAME> (in oracle database only table objects have flashback
and all objects are deleted permanently by drop command.)

To again create that package object:


@<package_name>

To display how many methods in a user:

41 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

To display the source code off a procedure or a function:


User can use a dictionary called USER_SOURCES
EX:

~O~

42 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

BULK ARRAY

BULK ARRAY PROGRAM:


DECLARE
cursor c1 is
select * from emp;

type rectype is table of emp%rowtype;

rec rectype;
BEGIN
OPEN c1;

FETCH c1 bulk collect into rec;

CLOSE c1;

FOR i in 1..rec.count

LOOP
dbms_output.put_line('Employee No: '||rec(i).empno);
dbms_output.put_line('Employee Name: '||rec(i).ename);
dbms_output.put_line('Employee Salary: '||rec(i).sal);
dbms_output.put_line('Employee Job: '||rec(i).job);
dbms_output.put_line('Employee Hiredate: '||rec(i).hiredate);
dbms_output.put_line('==========================');
END LOOP;

END;
/

43 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

O/P –

~ O ~

44 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

EXCEPTION HANDLING
✓ EXCEPTION HANDLING is a concept or a technique through which user can handle the abnormal
behaviour of a program.
✓ Whenever an exception occurs during runtime system control will move to exception block, handles
the exception and exits out of the program normally.
✓ In PL/SQL, exception handling can be possible in a different manner i.e.
o Using built-in exception handler (system exception handler)
o Using user defined exception handler (application exception handler)
✓ Built-in exception handler handlers are predefined programs responsible to handle a specific type
of error at runtime.
✓ Whereas user defined exception handlers are explicitly designed, thrown and handled by the user.

WORKING WITH BUILT-IN EXCPTION HANDLERS:


✓ Following are the frequently used built-in exception handlers to be used inside a program.

Oracle Database
Exception name error number SQLCODE Description
ACCESS_INTO_NULL ORA-06530 -6530 Program attempted to assign values to
the attributes of an uninitialized object.

CASE_NOT_FOUND ORA-06592 -6592 None of the choices in the WHENclauses of


a CASE statement were selected and
there is no ELSEclause.

COLLECTION_IS_NULL ORA-06531 -6531 Program attempted to apply collection


methods other than EXISTS to an
uninitialized nested table or varray, or
program attempted to assign values to
the elements of an uninitialized nested
table or varray.

CURSOR_ALREADY_OPENED ORA-06511 -6511 Program attempted to open an already


opened cursor.

DUP_VAL_ON_INDEX ORA-00001 -1 Program attempted to insert duplicate


values in a column that is constrained by
a unique index.

INVALID_CURSOR ORA-01001 -1001 There is an illegal cursor operation.

INVALID_NUMBER ORA-01722 -1722 Conversion of character string to number


failed.

NO_DATA_FOUND ORA-01403 +100 Single row SELECT returned no rows or


your program referenced a deleted
element in a nested table or an
uninitialized element in an associative
array (index-by table).

PROGRAM_ERROR ORA-06501 -6501 PL/SQL has an internal problem.

ROWTYPE_MISMATCH ORA-06504 -6504 Host cursor variable and PL/SQL cursor


variable involved in an assignment

45 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

statement have incompatible return


types.

STORAGE_ERROR ORA-06500 -6500 PL/SQL ran out of memory or memory


was corrupted.

SUBSCRIPT_BEYOND_COUNT ORA-06533 -6533 A program referenced a nested table or


varray using an index number larger than
the number of elements in the collection.

SUBSCRIPT_OUTSIDE_LIMIT ORA-06532 -6532 A program referenced a nested table or


varray element using an index number
that is outside the legal range (for
example, -1).

SYS_INVALID_ROWID ORA-01410 -1410 The conversion of a character string into


a universal rowid failed because the
character string does not represent
a ROWID value.

TOO_MANY_ROWS ORA-01422 -1422 Single row SELECT returned multiple


rows.

VALUE_ERROR ORA-06502 -6502 An arithmetic, conversion, truncation, or


size constraint error occurred.

ZERO_DIVIDE ORA-01476 -1476 A program attempted to divide a number


by zero.

SYNTAX:
DECLARE
<declarations section>

BEGIN
<executable command(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;

46 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Example of built-in exception handler using anonymous block:


set serveroutput on
set verify off
cl scr

DECLARE
vempno number(4);
vname varchar2(10);
vsal number(7,2);
vjob varchar2(10);
BEGIN
select empno,ename,sal,job
into vempno,vname,vsal,vjob
from emp where job=upper('&job');

dbms_output.put_line('Employee No: '||vempno);


dbms_output.put_line('Employee Name: '||vname);
dbms_output.put_line('Employee Salary: '||vsal);
dbms_output.put_line('Employee Job: '||vjob);
dbms_output.put_line('====================');

EXCEPTION
when no_data_found then
dbms_output.put_line('Record not found....Plz try again.');

mypack.ourprogdno(20);

for i in 1..10 loop


dbms_output.put_line('Hello sysoft...');
end loop;

when too_many_rows then


dbms_output.put_line('Plz use explicit cursor.....');

when others then


dbms_output.put_line('Other Error found...');
END;
/
O/P –

47 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

WORKING WITH USER DEFINED EXCEPTION USING SUBPROGRAM:

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 simple syntax for raising an exception −

DECLARE
<exception_name> EXCEPTION;
BEGIN
IF <condition> THEN
RAISE <exception_name>;
END IF;
EXCEPTION
WHEN <exception_name> THEN
statement;
END;

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 −

DECLARE
<exception_name> 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.

48 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

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;
/

When the above code is executed at the SQL prompt, it produces the following result

Enter value for cc_id: -6 (let's enter a value -6)


old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!

PL/SQL procedure successfully completed.

49 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

Example 2

create or replace package mypack


is

procedure ourprogins(vempno number,vname varchar2,vsal number,vjob varchar2);

END mypack;
/

create or replace package body mypack


as

procedure ourprogins(vempno number,vname varchar2,vsal number,vjob varchar2)


is
ex exception;

BEGIN
IF (vsal < 2000) then
RAISE ex;
ELSE
insert into employeetab
values(vempno,vname,vsal,vjob);

commit;
dbms_output.put_line('Record Inserted...');
END IF;
EXCEPTION
when ex then
dbms_output.put_line('Enter salary >= 2000...');
when others then
dbms_output.put_line('Other error found.....');
END ourprogins;

END mypack;
/

O/P –

50 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

TRIGGER
✓ TRIGGER is a special type of program automatically executed whenever a DML operation is made in an
ORACLE database.
✓ Trigger is identical with procedure. But the basic difference between them is, Procedure is explicitly created
and explicitly executed by the user whereas trigger is explicitly created but implicitly executed or fired
whenever a DML operation is made in an ORACLE database.
✓ Trigger program is widely used for transaction processing jobs.

TYPES OF TRIGGER:
1. Statement type: It is a type of trigger which will be executed once when any number of records
tampered by a DML operation.

2. Row type: It is a type of trigger which will be executed that many number of times the number of
records tampered by DML operation.

EVENTS OF A TRIGGER:
1. BEFORE: It is a type of event which will be executed just before the DML operation is made.
2. AFTER: It is a type of event which will be executed just after the DML operation is made.
✓ User can write the following trigger program depending upon their requirements –
o Statement type before/ statement type after
o Row type before/ row type after

SYNTAX TO CREATE A TRIGGER:


CREATE [OR REPLACE] TRIGGER <t_name>
AFTER|BEFORE INSERT OR UPDATE OR DELETE ON <tab_name>
[FOR EACH ROW]

[DECLARE
VARIABLE DEC;
TYPE DEC;
ARRAY DEC;
CURSOR DEC;]

BEGIN
IF INSERTING THEN
statement;
statement;
END IF;

IF DELETING THEN
statement;
statement;
END IF;

51 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

IF UPDATING THEN
statement;
statement;
END IF;
END <t_name>;
/

Example of a general trigger:


CREATE or REPLACE TRIGGER gentrig
after INSERT or UPDATE or DELETE on emptab
for each row

BEGIN

IF INSERTING THEN
dbms_output.put_line ('record INSERTED.....');

END IF;

IF UPDATING THEN
dbms_output.put_line ('record UPDATED.....');

END IF;

IF DELETING THEN
dbms_output.put_line ('record DELETED.....');

END IF;

END gentrig;
/
O/P –

52 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

✓ Above example is an example of row type after trigger.


✓ A trigger can call a subprogram sub program such as procedure and function.
✓ A trigger can also use cursor program within itself.
✓ A table can have maximum 12 triggers.

IMPLIMENTATION OF TRIGGER IN BACKUP TABLE:

• CREATION OF THE BACKUP TABLE IN ANOTHER SCHEMA (SYSTEM)


• Default is a keyword for retrieving current system date and time values.

• GRANTING PRIVILAGES ON THE BACKUP TABLE TO ANOTHER SCHEMA (SCOTT)

53 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

CREATING THE TRIGGER:


create or replace trigger employeetrig
after insert or update or delete on employee
for each row

BEGIN

IF INSERTING THEN

insert into system.employeebackup(empno,name,old_sal,new_sal,job,ttype)


values(:new.empno,:new.ename,null,:new.sal,:new.job,'Insert');\

END IF;

IF DELETING THEN

insert into system.employeebackup(empno,name,old_sal,new_sal,job,ttype)


values(:old.empno,:old.ename,:old.sal,null,:old.job,'Delete');

END IF;

IF UPDATING THEN

insert into system.employeebackup(empno,name,old_sal,new_sal,job,ttype)


values(:old.empno,:old.ename,:old.sal,:new.sal,:old.job,'Update');

END IF;

END employeetrig;
/
• CREATING TRIGGER IN THE SCHEMA OF WHICH TABLE IS GOING TO BE MANIPULATED.
• :old, :new are 2 pseudo variables which holds a value for temporary period whenever a triggering
event occurs on an particular table. For example:

54 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

O/P –

• FOR EVERY MANIPULATION MADE IN THE EMPLOYEE TABLE THE RECORD ARE GOING TO BE
STORED INSIDE THE BACKUP TABLE CREATED IN SYSTEM SCHEMA.

55 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012


AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385

HOW TO FIND TRIGGER IN THE DICTIONARY:

TO DROP A TRIGGER:

TO DISABLE A TRIGGER:

TO EABLE A TRIGGER:

~O~
THE END

56 | P a g e SYSOFT TECHNOLOGY: AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012

You might also like