PLSQL
PLSQL
Version 1.0
Day 1
– Module 1: Introduction to PL/SQL
– Module 2: PL/SQL Programming Constructs
– Module 3: PL/SQL Language Features
– Module 4: SQL in PL/SQL
– Module 5: Control Structures
Day 2
– Module 6: Stored sub programs (Stored Procedures &
Functions)
– Module 7: Cursors and Data Types as in 3GL
Version 1.0 2
PL/SQL (Contd.).
Day 3
– Module 8: Cursors
– Module 9: Packages
Day 4
– Module 10: Exceptions
– Module 11: Triggers
– Module 12: Dependencies among PL/SQL Constructs
Version 1.0 3
Module 1:
Introduction to PL/SQL
Version 1.0 5
What is PL/SQL Block
Version 1.0 6
Why PL/SQL?
Version 1.0 7
PL/SQL Engine
Version 1.0 8
Where PL/SQL stands?
Front end
application Program
…
…. Query
Invoking
PL/SQL SQL DATABASE
PL/SQL
PROCEDURE Data
….
….
………………..SERVER…………..……..
Version 1.0 9
PL/SQL Block
[Declare
Begin
[ Exception]
….
End;
Version 1.0 10
Advantages of PL/SQL
Block structured
– SQL statements are grouped and send as one
consolidated request to the server.
Improved Performance
– Network traffic can be reduced
Security
– Access to the data through PL/SQL
– Limited actions allowed over the table through
PL/SQL
Portable
– Work wherever Oracle Works
Version 1.0 11
Advantages-Contd.
Compatibility
– Supports all the data types available in
Oracle/SQL.
Stored Procedures
– Additional Features like Stored procedures
and Triggers are included
– Stored Procedures are available in the server
as database objects and is ready to execute
Version 1.0 12
Nesting of Blocks
Version 1.0 13
Module 2:
PL/SQL Program Constructs
Anonymous
Block Packages
PL/SQL
BLOCK
Stored
Procedure Triggers
/Programs
Procedures Functions
Version 1.0 15
Anonymous Block
Version 1.0 16
Stored Procedures
Version 1.0 17
Packages
Version 1.0 18
Triggers
Version 1.0 19
Module 3:
PL/SQL Language Features
Declare
v_designation varchar2(15); Variable declaration
Begin
select job
into v_designation Data Retrieval from Table
into Variable
from emp
where ename='SCOTT';
if (v_designation = 'MANAGER') then
update emp set sal=sal*1.5 where ename='SCOTT';
else
update emp set sal=sal*1.05 where ename='SCOTT';
End if;
End;
Version 1.0 21
Lexical Unit
Character Set
– Alphabets (both upper and lower)
– Numerals
– Special Characters like #,%,$,etc.,
Commenting
– Two Consecutive hyphens -- for single line
comment and /*…..*/ for multi line comments
Delimiter
– Every statement in PL/SQL Block is separated
using semicolon(;)
Version 1.0 22
Variables
Version 1.0 23
Rules-Identifier
Version 1.0 24
Data Types
Version 1.0 25
Declaration - Example
Syntax is
Variable Name Data Type [ DEFAULT ]
[ NOT NULL ] [ NULL ];
Example
Salary Number(7,2);
HRA Number(7,2) default 3000;
DA Number(7,2):=2000;
Version 1.0 26
Declaration
Version 1.0 27
Scope & Visibility of Variables
(In nested Blocks)
Declare
A number: =200;
BEGIN
…….
Declare --Inner Block Starts
A number:=100; What would be
BEGIN the value of A?
DBMS_OUTPUT.PUT_LINE(A); -- Print A
…..
END; -- Inner Block ends
A is 100 or
DBMS_OUTPUT.PUT_LINE(A); 200?
END;
Version 1.0 28
LABEL << … >>
<<outer>>
Declare
A number: =200;
BEGIN
…….
Declare --Inner Block Starts
A number:=100; Print 100
BEGIN and then 200
DBMS_OUTPUT.PUT_LINE(A || outer.A);
…..
END; -- Inner Block ends
DBMS_OUTPUT.PUT_LINE(A);
END;
Version 1.0 29
Operators-Assignment
Version 1.0 30
Operators
Arithmetic Operators
– * , / , + , - ,mod
Comparison Operators
– Relational Operators
• <, <=, >, >=, = and != or <> or ~=
– IS NULL, LIKE,BETWEEN,IN
Logical Operators
– NOT, AND, OR
Version 1.0 31
Built-in-Functions
Number
Character
Conversion
Date
Error Reporting
Others
Version 1.0 32
Number Functions
ROUND
TRUNC
MOD
POWER,SQRT
COS,SIN,TAN,LOG,
Version 1.0 33
Character Function
Version 1.0 34
Date -Function
Sysdate
Last_day
Months_between
Round
Trunc
Add_months
New_time
Next_day
Version 1.0 35
Conversion Function
To_char
To_date
To_number
Chartorowid
Rowidtochar
Hextoraw
rawtohex
Version 1.0 36
Error Reporting Functions
SQLERRM
SQLCODE
Version 1.0 37
Others - Functions
DECODE
GREATEST
LEAST
NVL
USER
Version 1.0 38
Module 4:
SQL In PL/SQL
Version 1.0 40
INTO Clause
(Data From SQL into PL/SQL)
Version 1.0 41
INTO Clause - Example
DECLARE
v_name varchar2(10);
v_dno number(2);
BEGIN
SELECT ename, deptno
Version 1.0 42
Example – 2
DECLARE
v_name varchar2(10);
Begin
SELECT ename
INTO v_name
FROM emp
WHERE deptno=10;
end;
What is wrong with this query?
Will this query work if there are more that 1 employee
working for deptno 10 ?
Will this query work if there are no employees working
for deptno 10?
Version 1.0 43
Restrictions
Version 1.0 44
DML in PL/SQL
Begin
v_eno:=7782;
v_new_mgr:=7788
update emp set mgr=v_new_mgr where mgr=v_eno;
insert into dept values(60,’FINANCE’,’TEXAS’);
delete emp where empno=v_eno;
end;
DML commands can be executed through PL/SQL without
any modification in the syntax.
DML Can use compatible data items
Version 1.0 45
TCL in PL/SQL
DECLARE
v_sal number(7,2);
BEGIN
update emp set sal=sal*1.50;
select sum(sal)
into v_sal
from emp;
if v_sal > 1000000 then
rollback;
else
commit;
end if;
END;
Version 1.0 46
& Substitution Variable
Version 1.0 47
Host variables
Version 1.0 48
Bind variables - Example
PL/SQL Block 1
Begin
a:=:x; --acts as global variable
:x:=:x + a; --assign 20 to variable x
end;
PL/SQL Block 2
begin
dbms_output.put_line (:x); --prints 20
end;
Version 1.0 49
Module 5:
Control Structures
Version 1.0 51
Conditional Statements
Version 1.0 52
IF Statement -Example
Example 1:
IF (V_JOB=‘CLERK’) THEN
V_BONUS:=2000;
END IF;
Example 2:
IF (V_JOB=‘SALESMAN’) THEN
V_BONUS:=2000;
ELSE
V_BONUS:=1000;
END IF;
Version 1.0 53
IF –THEN-ELSE
Example 3:
IF (V_JOB=‘SALESMAN’) THEN
V_BONUS:=2000;
ELSE
IF (V_JOB=‘CLERK’) THEN
V_BONUS:=3000;
ELSE
V_BONUS:=1000;
END IF;
END IF;
Version 1.0 54
ELSIF -Example
Example 4:
IF (V_JOB=‘SALESMAN’) THEN
V_BONUS:=4000;
ELSIF (V_JOB=‘CLERK’) THEN
V_BONUS:=3000;
ELSIF (V_JOB=‘ANALYST’) THEN
V_BONUS:=2000;
ELSE
V_BONUS:=1000;
END IF;
Version 1.0 55
CASE
Version 1.0 56
Looping Constructs
Version 1.0 57
LOOP…END LOOP
LOOP
…..
…..
END LOOP
Statements between LOOP and END LOOP will
be executed repeated and also infinitely
Use EXIT to terminate the endless looping
Version 1.0 58
EXIT
LOOP
…..
EXIT;
….
END LOOP
…..
Version 1.0 59
EXIT WHEN - Example
Loop
…
EXIT WHEN CNT>10;
…
END LOOP;
IF (CNT>10) THEN
DBMS_OUTPUT.PUT_LINE (‘Exceeded limit 10’);
EXIT;
END IF;
Version 1.0 60
WHILE LOOP
WHILE (condition)
LOOP
…
END LOOP;
Statements between LOOP and END LOOP will
be executed while the condition is true
Toggle the condition in loop body - to avoid
infinite looping
Version 1.0 61
FOR LOOP
Version 1.0 62
FOR LOOP - Example
Version 1.0 63
NULL - Statement
Version 1.0 64
Module 6:
Stored Sub Programs
Modular approach
Improved Maintenance
Stored in an executable format
Stored as Database objects in the server
Security
Parameterized
Version 1.0 66
Types of Parameters
Formal Parameters
Actual Parameters
Version 1.0 67
Module 6.1:
Stored Procedures
IN Parameter
– To send input values to the sub program
OUT Parameter
– Carry output values to the calling environment
IN OUT Parameter
– Used in both the directions to send and carry
from the sub block to the calling block
Version 1.0 69
IN Parameter
Version 1.0 70
OUT Parameter
Version 1.0 71
IN OUT Parameter
Version 1.0 72
Creating the Procedure
Version 1.0 73
Procedure - Example
Version 1.0 75
Invoking the Procedure
Version 1.0 76
Invoking the Procedure
To call the procedure “retrieve” with 1 IN
parameter and 2 OUT parameters from an
anonymous block
Declare
v_name varchar2(15);
v_job varchar2(15);
Begin
retrieve(7788,v_name,v_job);
End;
Version 1.0 77
Removing the Procedure
Syntax is
DROP PROCEDURE procedure_name;
Example
drop procedure retrieve;
Version 1.0 78
Data Dictionary Views
DESC procedure_name
DESC USER_SOURCE
DESC USER_OBJECTS
DESC USER_DEPENDENCIES
Version 1.0 79
Module 6.2:
Stored Functions
Version 1.0 81
Creating the Functions
Syntax is
CREATE [OR REPLACE] FUNCTION function_name
[(Formal parameter1 [MODE] Data_type,
Formal parameter2 [MODE] Data_type,
….)]
RETURN Data_type
IS|AS
PL/SQL Block;
Version 1.0 82
Return Statement
RETURN data_type
– Only type has to be specified and size
specification is not allowed
– Can be Scalar data type and composite data
types.
– Can return only one value
– Should have at least one return statement in
the PL/SQL block
• RETURN variable;
Version 1.0 83
Example
Version 1.0 84
Invoking the Function
SQL:>execute :salary:=ret_maxsal(10)
select ename
from emp
where sal>ret_maxsal(20);
Version 1.0 85
Removing the Function
Example
– DROP FUNCTION ret_maxsal
Will remove the stored function ret_maxsal.
Also remove the related data dictionary
entries and contents.
Version 1.0 86
Restrictions on using functions
Version 1.0 87
Procedures Vs Functions
PROCEDURE FUNCTION
Version 1.0 88
Data Dictionary Views
DESC function_name
DESC USER_SOURCE
DESC USER_OBJECTS
DESC USER_DEPENDENCIES
DESC USER_ERRORS
Version 1.0 89
Module 7:
Cursors and Data types
(as in 3GL)
DATA DICTIONARY
Declare
DESC EMP
V_SAL EMP.SAL%TYPE;
…..
SAL NUMBER(7,2)
….
NUMBER(7,2)
Version 1.0 91
%Type
Declare
v_sal emp.sal%type;
…
– Implicit data type (structure) specification.
– Refer the data dictionary for EMP table.
– Fetch the current data type of SAL column.
– Map it for the variable v_sal.
Version 1.0 92
%TYPE - Example
Example 1
DECLARE
var1 NUMBER(7,2);
var2 var1 %TYPE;
Example 2
DECLARE
sal emp.sal%TYPE;
eno NUMBER(4);
Version 1.0 93
Example - 1
Retrieve all the columns of particular employee
Declare
V_eno number(4);
V_name varchar2(15);
V_job varchar2(10);
V_mgr number(4);
V_hiredate date;
V_sal number(7,2);
V_comm number(7,2);
V_dno number(2);
Begin
Select *
Into v_eno,v_ename,v_job,v_mgr,v_hiredate,v_sal,
v_comm,v_dno
……
Version 1.0 94
%ROWTYPE
Declare
myemp emp%rowtype;
Begin
select *
into myemp
….
if (myemp.comm is not null) then …
Structure of emp table is referred and copied to
variable myemp.
To access the variables use rowtype variable and
name of the column. i.e.,myemp.comm
Version 1.0 95
Record Type
Version 1.0 96
Record Type - Example
DECLARE
TYPE my_data is RECORD
(ename emp.ename%TYPE,
dname dept.dname%TYPE);
my_emp my_data;
BEGIN
SELECT ename,dname
INTO my_emp
FROM emp,dept
WHERE emp.deptno=dept.deptno AND empno=&ENO;
dbms_output.put_line(my_emp.ename ||
my_emp.dname);
END;
Version 1.0 97
Record Type - Example
Version 1.0 98
PL/SQL Table
Version 1.0 99
PL/SQL Tables-Example
Implicit Cursors
– Handled and controlled by Oracle
– System defined cursors
– Memory area used temporarily for fetching
and DML operation
Explicit Cursors
– Defined ,Named and used by programmer
– Controlled by user
SQL%ROWCOUNT
– Number of rows affected by the most recent SQL
statement
SQL%FOUND
– TRUE if the most recent SQL found any row
– Set to TRUE if SQL%ROWCOUNT is <>0
SQL%NOTFOUND
– TRUE if the most recent SQL didn’t find any row
– Set to true if SQL%ROWCOUNT is =0 or SQL
%Found is false
SQL%ISOPEN
– Always FALSE because control will be transferred
to the user after closing implicit cursor
Declare
dno number(4);
Begin
dno:=&depno;
delete from emp where deptno=dno;
if (sql%found) then
dbms_output.put_line (sql%rowcount);
end if;
if (sql%notfound) then
dbms_output.put_line ('no employees working for
deptno ‘||dno);
end if;
end;
START
No into in
DECLARE CURSOR select
Declare
Cursor my_cur is select ename,sal from emp;
OPEN CURSOR
open my_cur; Brings the active set
into the cursor area
NP
NP
IS
NO
EMPT
Y
YES
CLOSE CURSOR
close my_cur;
STOP
Example
Declare
Cursor my_cur is
select ename, sal from emp;
cur_rec my_cur%rowtype;
Begin
….
Fetch my_cur into cur_rec;
Example
Declare
….
v_ename emp.ename%type;
v_sal emp.sal%type;
Begin
….
Fetch my_cur into v_ename,v_sal;
%ROWCOUNT
– Number of rows fetched so far by the cursor
%FOUND
– TRUE if the most recent fetch operation found
any row
%NOTFOUND
– TRUE if the most recent fetch didn’t find any new
record in cursor’s active set
– Set to TRUE if %Found is FALSE
%ISOPEN
– Shows the status of the cursor
– TRUE if it is open else it is FALSE.
declare
cursor dep_cur is select * from emp where deptno=10 order by sal;
begin
dbms_output.put_line('-------------------------------');
dbms_output.put_line ('Sl.No. Salary details');
dbms_output.put_line('-------------------------------');
FOR dep_rec IN dep_cur
LOOP
dbms_output.put_line (dep_cur%rowcount||' '||dep_rec.ename
||'''s salary is '||dep_rec.sal);
END LOOP;
dbms_output.put_line('-------------------------------');
end;
Begin
FOR dep_rec IN (select * from emp where deptno=10 order by sal)
LOOP
…..
END LOOP;
End;
Declare
cursor dep_cur (v_did number) is
select count(*) cnt from emp where deptno=v_did ;
dep_rec dep_cur%rowtype;
Begin
open dep_cur(10); --Retrieve dept 10 employees
fetch dep_cur into dep_rec;
dbms_output.put_line (dep_rec. cnt);
close dep_cur;
open dep_cur(20); --Retrieve dept 20 employees
fetch dep_cur into dep_rec;
dbms_output.put_line (dep_rec. cnt);
close dep_cur;
end;
Syntax is
Select …..
FOR UPDATE [OF COLUMN] [NOWAIT]
Locks the ROWS being read for updating
Other user’s request for the rows locked will be
in the wait state
Locks can be released using rollback/commit
Example
– SELECT * FROM EMP WHERE DEPTNO=10
FOR UPDATE;
Syntax
WHERE CURRENT OF cursor name;
Used in Update & Delete commands
Refers the rows recently fetched by the cursor.
No additional specifier is needed to refer the
locked rows.
Example
– DELETE emp WHERE CURRENT OF
my_cur;
Declare
Cursor my_cur IS
Select * from emp where deptno=10
FOR UPDATE;
current_rec my_cur%rowtype;
Begin
….
FETCH my_cur INTO current_rec;
update emp set comm=1000
WHERE CURRENT OF my_cur;
……
Procedures
– Cursors
– And all PL/SQL allowed Constructs
Modularity
– Related modules are grouped and kept as one
collection
Interface
– Provides single and simple interface to access its
components
Sharable object
– Can be shared by many users at a time
Minimal disk I/O
– Loads the code into the memory when it is referred
for the first time
Extended Functionality
– Additional facility provided along with stored sub
programs
Security
– Decide upon the list of operations allowed over
the database objects
Global Access
– Declared variable are accessible from anywhere
– Data remains throughout the session
Overloading
– Is allowed with packaged sub programs and not
with stored sub programs
Syntax
CREATE [OR REPLACE] PACKAGE package_name
IS
Variable Declaration;
Sub Program header specification;
END [package_name];
Syntax
CREATE [OR REPLACE] PACKAGE package_name
IS
Variable Declaration;
Sub Program header specification;
END [package_name];
Example
CREATE OR REPLACE PACKAGE bonus_pack
IS
v_bonus NUMBER:=0;
PROCEDURE retrieve_bonus(p_eno NUMBER);
END bonus_pack;
SQL:>EXECUTE bonus_pack.v_bonus:=1000;
SQL:>EXECUTE bonus_pack.retrieve_bonus(7788);
BEGIN
bonus_pack.v_bonus:=200;
dbms_output.put_line(bonus_pack.v_bonus);
….
bonus_pack.retrieve_bonus(7369);
END;
Example
CREATE OR REPLACE PACKAGE dept_pack
IS
v_dept_cnt NUMBER:=0;
PROCEDURE print_details;
END dept_pack;
INTO v_dept_cnt
FROM DEPT;
END;
COUNT(*)
----------
5
DBMS_OUTPUT
UTL_FILE
DBMS_ALERT
DBMS_LOCK
DBMS_JOB
DBMS_SESSION
Syntax
….
EXCEPTION
WHEN name_of_exception1 THEN
handler – PL/SQL statements
WHEN name_of_exception2 THEN
handler
END;
Exception
Non-
Pre-defined User-
Predefined
Exception defined
Exception
DECLARE
unique_constraint EXCEPTION;
PRAGMA EXCEPTION_INIT(unique_constraint,-0001);
BEGIN
…..
INSERT INTO DEPT VALUES(10,'Finance','CA');
…..
EXCEPTION
WHEN unique_constraint THEN
DBMS_OUTPUT.PUT_LINE ('caught exception');
……
END;
PRAGMA EXCEPTION_INIT
– Associates name “unique constraint” with the error
code -0001
Exception got declared, handled and not invoked
Version 1.0 159
RAISE APPLICATION ERROR
….
RAISE_APPLICATION_ERROR(-20010,'Check Constraint
Violation');
…
ERROR at line 1:
ORA-20010: Check Constraint Violation
DECLARE
v_empno EMP.EMPNO%TYPE;
BEGIN
INSERT INTO DEPT VALUES(55,’Operations’,’NY’);
SELECT empno
INTO v_empno
FROM emp
WHERE ename=‘ABC’;
DBMS_OUTPUT.PUT_LINE (v_empno);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE (‘no employee found);
END;
DECLARE
…
When no_data_found
BEGIN
Exception is raised
….
BEGIN --Inner block begins
…..
EXCEPTION --Exception handler for inner block
WHEN NO_DATA_FOUND THEN
…..
END --Inner block ends
…..
…..
EXCEPTION --Exception handler for outer block
…….
……
END;
DECLARE
… When no_data_found Exception
is raised in inner block and
BEGIN
handled in both blocks
….
BEGIN --Inner block begins
…..
EXCEPTION --Exception handler for inner block
WHEN NO_DATA_FOUND THEN
…..
END --Inner block ends
…..
…..
EXCEPTION --Exception handler for outer block
WHEN NO_DATA_FOUND THEN
……
END;
DECLARE
… When no_data_found Exception
is raised in inner block and
BEGIN
handled in both blocks
….
BEGIN --Inner block begins
…..
EXCEPTION --Exception handler for inner block
WHEN NO_DATA_FOUND THEN
RAISE;
END --Inner block ends
…..
…..
EXCEPTION --Exception handler for outer block
WHEN NO_DATA_FOUND THEN
……
END;
TRIGGERS
Trigger timing
– When to fire trigger after the request or before
the current request
Triggering event
– For what event this trigger is to be fired
– Is it insert/update/delete
Table name
– Name of the table for which trigger is
Trigger type
– Two categories of trigger exist –decides upon
how trigger gets fired
– Statement level – once per request
– Row level – for each and every row got
affected trigger is executed
When clause
– Prepares selected rows for trigger action
– Allowed only for Row level trigger
Trigger body
– Explains what to be done in the trigger end
Version 1.0 171
Database Triggers
DESC USER_OBJECTS
DESC USER_SOURCE
DESC USER_ERRORS
DESC USER_TRIGGERS
DESC USER_OBJECTS
DESC USER_SOURCE
DESC USER_ERRORS
DESC USER_TRIGGERS
DESC USER_DEPENDENCIES