PL/SQL: by Lohit Mitra
PL/SQL: by Lohit Mitra
BY LOHIT MITRA
SYSOFT TECHNOLOGY
AMRITA COMPLEX, CRPF SQUARE, NAYAPALLI, BHUBANESWAR – 751012
AUTH: LOHIT MITRA SYSOFT TECHNOLOGY MOB: 9861033385
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.
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.
Dbms_output.put_line (V1);
Dbms_output.put_line (V2);
Dbms_output.put_line (V3); PROJECTION
…………………………………
…………………………………
Dbms_output.put_line (Vn);
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:
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');
✓ 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
BEGIN
select *
into rec
from emp
where ename = upper('&name');
select *
into rec2
from emp
where ename = upper('&name');
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.
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');
END;
/
OUTPUT –
✓ Above example shows once a structure is created user can declare several number of variables of
that structure.
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');
END;
/
9|Page 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;
SYNTAX:
LOOP
statement;
statement;
EXIT [WHEN <CONDITION>];
END LOOP;
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;
/
DECLARE
i number(4) := 1;
BEGIN
while (i <= 10)
LOOP
dbms_output.put_line(i);
i := i+1;
END LOOP;
END;
/
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;
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;
/
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
x myary;
y myary;
Variables of array type
total number(5) := 0;
BEGIN
x := myary(10,20,30,40,50); Type casting
LOOP
dbms_output.put_line(x(i));
total := total + x(i);
END LOOP;
dbms_output.put_line('======================');
dbms_output.put_line('TOTAL ='||total);
END;
/
Output:
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.
: 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 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”.
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;
END;
/
OUTPUT:
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;
BEGIN
FOR rec in c1 LOOP
ta := rec.sal*.1;
da := rec.sal*.12;
total := ta+da+rec.sal;
END IF;
END LOOP;
END;
/
O/P-
SYNTAX:
DECLARE
SELECT STATEMENT
WHERE COL_NAME = ARG;
BEGIN
OPEN < C_NAME > (VALUE / EXP);
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;
END LOOP;
CLOSE c1;
END;
/
BEGIN
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
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);
END;
/
O/P-
CURSOR
%NOTFOUND
%ISOPEN
ADVANCED / DYNAMIC CURSOR /
%ROWCOUNT
CURSOR WITH PARAMETER
(BASIC LOOP & FOR LOOP)
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
END <PRO_NAME>;
/
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.
BEGIN
for i in 1..10 loop
fsubprog;
end loop;
END subprog1;
/
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.
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.
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 ~
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);
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;
/
return (da);
end fda;
/
begin
totalsal:=vsal+vta+vda;
return(totalsal);
end ftotalsal;
/
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;
/
O/P –
NOTE: Once a stored function is created, the function can be used in query statement to accomplish a
specific job.
Ex:
~ O ~
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.
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;
..........................
.................
.........
END <P_NAME>;
/
BEGIN
dbms_output.put_line('Our first package programme...');
END ourprogdisplay;
BEGIN
insert into employeetab
values(vempno,vname,vsal,vjob);
COMMIT;
END ourprogins;
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;
END ourprogdno;
END mypack;
/
o/p –
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.)
~O~
BULK ARRAY
rec rectype;
BEGIN
OPEN c1;
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;
/
O/P –
~ O ~
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.
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.
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;
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');
EXCEPTION
when no_data_found then
dbms_output.put_line('Record not found....Plz try again.');
mypack.ourprogdno(20);
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.
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.
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
−
Example 2
END mypack;
/
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 –
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
[DECLARE
VARIABLE DEC;
TYPE DEC;
ARRAY DEC;
CURSOR DEC;]
BEGIN
IF INSERTING THEN
statement;
statement;
END IF;
IF DELETING THEN
statement;
statement;
END IF;
IF UPDATING THEN
statement;
statement;
END IF;
END <t_name>;
/
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 –
BEGIN
IF INSERTING THEN
END IF;
IF DELETING THEN
END IF;
IF UPDATING THEN
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:
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.
TO DROP A TRIGGER:
TO DISABLE A TRIGGER:
TO EABLE A TRIGGER:
~O~
THE END