02 - PL-SQL - Oracle PL SQL Training Manual
02 - PL-SQL - Oracle PL SQL Training Manual
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
1. Introduction
3. Blocks
i. Unnamed or anonymous block
ii. Named or stored procedures
iii. Labeled blocks
5. Cursors
i. Implicit
ii. Explicit
iii. Ref cursor
7. stored procedure
i. procedures
ii. functions
iii. packages
iv. triggers
8. pragmas
9. no copy
10. forward declaration
11. bulk collect & bulk bind
12. mutating triggers
13. dynamic sql (execute immediate)
14. table function
15. advanced topics
This is a procedural language or programming language
It consist of unit blocks
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Blocks:
Unnamed Blocks:-
Syntax:
Declarative Section:-
We use declarative section to define variables, constants, cursors, exceptions, etc.,
We have to define the things in declarative section which are not understand by PL/SQL engine which is
optional?
Excitable Section:-
Here we define or we provide coding path
Execution takes place in executable section which is mandatory
It starts from begin to end
Exception section:-We use exception section to handle runtime errors and which is optional
Declare
begin
Declare
begin
Outer block
or code; Inner block
Enclosing Block
Exception
End;
Exception
End;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Begin
Begin
End;
End;
Example:-
1. Write a program to display the message on to the screen?
begin
dbms_output.put_line('hello welcome to pl/sql');
dbms_output.put_line('this is OracleApps88.Blogspot.com');
end;
Output:-
End;
Begin
o/p not coming w/o using stmt.
End;
2 Using Constant:- We don’t change modifications in entire block
DECLARE
A CONSTANT NUMBER (5, 3) := 3.142;
B NUMBER (5) := 100;
BEGIN
B := 50;
DBMS_OUTPUT.put_line (a + b);
END;
Output:
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End;
4. Write a program to calculate the area of the circle by knowing the radius
DECLARE
a NUMBER (5, 3);
r NUMBER (5) := &n;
p CONSTANT NUMBER (5, 3) := 3.142;
BEGIN
a := p * POWER (r, 2);
2) Composite datatypes
a) %type
Ex:-Write a program to retrieve and display the employee name by providing employee number?
declare
vno number(5):=&n;
vname varchar2(10);
begin
select ename into vname from emp where empno = vno;
dbms_output.put_line('employee name'||vname);
end;
/
Output:-
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Ex:-variable emp.ename%type;
DECLARE
vno emp.empno%TYPE := &n;
vname emp.ename%TYPE;
BEGIN
SELECT ename
INTO vname
FROM emp
WHERE empno = vno;
Output:
Disadvantage:- by using %rowtype it is not possible to store table record along with user data or user
information
4. CONTROL STATEMENTS
Control flow
1. if statement
2. case statement
1. If condition:
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Syntax:-
if condition then
Do1; (stmts)
Else if condition then
Do2; (stmts)
Else do3; (stmts)
End if;
2. Nested if:
Syntax:-
If condition then
Do1;
If condition then
Do3;
Else
Do4;
End if;
Else
Do2;
End if;
Ex:-
DECLARE
v NUMBER (5) := &n;
BEGIN
IF v > 1000
THEN
DBMS_OUTPUT.put_line ('hellow given number is > 1000');
ELSE
DBMS_OUTPUT.put_line ('number is < 1000');
END IF;
END;
/
Output:-
Case:
1. Simple case
2. Search case
Syntax:
Case [columns/expressions]
When condition then
Do1; (stmts)
When condition then
Do2; (stmts)
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
2. Search case:
Ex:-
SELECT sal,CASE WHEN sal =5000
THEN'A'
WHEN sal >=3000
THEN'B'
ELSE'C'
ENDCASE,job, deptno
FROMemp
Output:
Ex:-
SELECTSUM(CASE
WHEN sal =5000
THEN sal
WHEN sal >=3000
THEN sal
ELSE sal
END
) sum_sal
FROMemp
Output:
Ex:-
DECLARE
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
vsal emp.sal%TYPE;
vno emp.empno%TYPE := &n;
BEGIN
SELECT sal
INTO vsal
FROM emp
WHERE empno = vno;
CASE
WHEN vsal = 5000
THEN
DBMS_OUTPUT.put_line ('sal = 5000');
WHEN vsal >= 3000
THEN
DBMS_OUTPUT.put_line ('sal = 3000');
ELSE
DBMS_OUTPUT.put_line ('sal < 3000');
END CASE;
END;
/
Output:
Note:- In the absence of else part if all of the conditions are false then it throws on an error i.e. case not found.
(it throws err ORA-06592, pls check below o/p)
Ex:-
DECLARE
vsal emp.sal%TYPE;
vno emp.empno%TYPE := &n;
BEGIN
SELECT sal
INTO vsal
FROM emp
WHERE empno = vno;
CASE
WHEN vsal > 5000
THEN
DBMS_OUTPUT.put_line ('sal = 5000');
WHEN vsal > 6000
THEN
DBMS_OUTPUT.put_line ('sal = 6000');
END CASE;
END;
/
Output:
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
CASE vsal
WHEN 5000
THEN
DBMS_OUTPUT.put_line ('sal = 5000');
WHEN 3000
THEN
DBMS_OUTPUT.put_line ('sal = 3000');
ELSE
DBMS_OUTPUT.put_line ('sal < 3000');
END CASE;
END;
/
Output:
c) Iterations:
Loops:- to execute the same statement or coding for repeated times we use loops
1. Simple loop
2. While loop
3. for loop
a. Numeric for loop
b. Cursor for loop
1. Simple loop:- it is an infinite loop explicitly we have to stop the loop. It is uses in blocks.
Syntax:-
Loop
Code;
End loop;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Ex:-
Begin
Loop
Exit [when condition];
Code;
End loop;
End;
DBMS_OUTPUT.put_line (x);
x := x + 1;
END LOOP;
END;
/
Output:
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Ex:-
SELECT deptno,SUM(NVL(sal,100)) sum_sal
FROMemp
GROUPBY deptno
HAVINGSUM(sal)>200
Output:
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Ex:-
DECLARE
x NUMBER (5) := 1;
y NUMBER (5) := 1;
BEGIN
LOOP
y := 1;
LOOP
DBMS_OUTPUT.put_line (x || '*' || y || '=' || x * y);
y := y + 1;
EXIT WHEN y > 10;
END LOOP;
x := x + 1;
EXIT WHEN x > 10;
END LOOP;
END;
/
Output:
Write a program to reverse the give string by using simple loop (without using reverse function)
For loop:
Syntax:
For var in [reverse] val1..val2 loop
Code;
End;
Ex:-Begin
For I in 1..10 loop
Dbms_output.put_line(i);
End loop;
End;
Ex:-
Begin
For I in reverse 1..10 loop
Dbms_output.put_line(i);
End loop;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End;
Ex:-
Begin
For I in 1..10 loop
If I <5 then
Continue;
End if;
Dbms_output.put_line(i);
End loop;
End;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
CURSORES
Oracle will make use of internal memory areas (implicit cursors) for sql statements to process the records
This memory areas will be defined in a area called SGA (system global area)
Oracle allows to provide our own memory areas (explicit cursors) to get control over each of the record
Cursor functionalities:
Step 1: Declaring the cursor
Syntax:-cursor cursor_name is select …
Step 2:opening a cursor
Syntax: open cursor_name
Step 3: Fetching records into variable from cursor
Syntax: fetch cursor_name into variable;
Step 4: closing cursor
Syntax: close cursor_name
Cursor Attributes
1. Cursor_name%isopen;
2. Cursor_name%found;
3. Cursor_name%notfound;
4. Cursor_name%rowcount;
5. Cursor_name%bulk_rowcount;
6. Cursor_name%bulk_exception; (save exception 11g)
Ex: Declare
Cursor c is select ename for emp;
Vname emp.ename%type;
Begin
Open c;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Loop
Fetch c into vname;
Exit when c%notfound;
Dbms_output.put_line(vname);
End loop;
Close c;
End;
Parameterised Cursors:
In cursors we use “In” parameters
Ex:
Declare
Cursor c(x emp.deptno%type) is select ename from emp where deptno = x;
Vname emp.ename%type;
Vno number(5):=&n;
Begin
Open c(vno);
Loop
Fetch c into vname;
Exit when c%notfound;
Dbms_output.put_line(vname);
End loop;
Close c;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End;
Static cursors:
we can open the cursor n no.of times
Ex:-
Declare cursor c is select ename from emp;
Vname emp.ename%type;
Begin
Open c;
Loop
Fetch c into vname;
Exit when c%notfound;
Dbms_output.put_line(vname);
End loop;
Close c;
Open c;
End;
a) Implicit Cursors
Declare
Vno emp1.deptno%type:=&n;
Begin
Delete from emp1 where deptno = vno;
If sql%rowcount >3 then
Dbms_output.put_line(sql%rowcount||’employees not possible to delete’);
Rollback;
Else
Dbms_output.put_line(sql%rowcount||’employees possible to delete’);
Commit;
End if;
End;
We use implicit cursors to find out the status of DML operations.
REF CURSOR
Ref cursor is a datatype
We use ref cursors to handle multiple select statements
We can pass ref cursor variable to a parameter value
Syntax: type typename is ref cursor;
Var typename;
Ex:-
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Declare
Type rec is refcursor;
Vrec rec;
Vemp emp.ename%type;
Vdept dept.loc%type;
Begin
Open vrec for select ename from emp;
Loop
Fetch vrec into vemp;
Exit when vrec%notfound;
Dbms_output.put_line(vemp);
End loop;
Close vrec;
Dbms_output.put_line(‘++++++++’);
Open vrec for select dname from dept;
Loop
Fetch vrec into vdept;
Exit when vrec%notfound;
Dbms_output.put_line(vdept);
End loop;
Close vrec;
End;
Ex:-
Declare
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Cursor expressions:
EXCEPTIONS
Basically or generally errors are of two types
1. Syntactical
2. Runtime
We will get syntactical errors ar compilation time they itself we can rectify the compilation errors
To handle the runtime errors we use exceptions
Types of exceptions
User defined
Pre-defined
Non predefined
In user defined exceptions user has to declared the exceptions, raise and the handle the exceptions
We handle the errors in exception section by using exception handlers
Whereas in the case of predefined manufacturer as to define system has to raise and user as to handle
Syntax
Declare
Exceptioname exception;
Begin
Raise exceptionname;
Exception
When exceptionname then
When
Exception then
End;
Predefined Exceptions
Ex:-
Declare
Vno emp.empno%type :=&n;
Vname emp.ename%type;
Begin
Select ename into vname from emp where empno = vno;
Dbms_output.put_line(‘hello’);
Exception
When too_many_rows then
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
User_defined exceptions:
Declare
Ex exception;
Vno emp.empno%type :=&n;
Vrow emp%rowtype;
Begin
Select * into vrow from emp where empno = vno;
If vrow.comm is null then
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
END;
NOTE: It throws an error. Others should not be at first in the list of exceptions. It should be always at last
among exceptions.
CASE: 2
DECLARE
----------------;
BEGIN
----------------;
EXCEPTION
WHEN EX1 OR EX2 THEN;
---------------------------------------;
END;
NOTE: It is possible to mention the exception in series by separating with ‘OR’ operator.
CASE: 3
DECLARE
-------------
BEGIN
-------------
EXCEPTION
WHEN EX1 OR OTHERS THEN;
-----------------------------------------------
END;
NOTE: It is not possible to mention the exception in series by separating with’OR’ operator.
CASE: 4
DECLARE
----------------;
BEGIN
----------------;
EXCEPTION
WHEN EX1 AND EX2 THEN;
------------------------------------------;
END;
NOTE: It is not possible to mention the exception in series by separating
with AND operator.
CASE: 5
DECLARE
------------------
BEGIN
BEGIN
RAISE EX;
EXCEPTION;
WHEN EX2 THEN;
END;
EXCEPTION
WHEN EX THEN;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
END;
NOTE: Exceptions raised in inner block can be handled in the outer
block. This is called as EXCEPTION PROPAGATION.
CASE:6
DECLARE
---------------;
BEGIN
RAISE EX2;
BEGIN
RAISE EX;
EXCEPTION
WHEN EX2 THEN;
END;
EXCEPTION
WHEN EX THEN;
END;
NOTE: Exception raised in outer block cannot be handled in inner block.
CASE: 7
DECLARE
----------------
BEGIN
BEGIN
RAISE EX
EXCEPTION
WHEN EX THEN;
--------------------------
RAISE
WHEN EX THEN;
-----------------------;
END;
EXCEPTION
WHEN EX THEN;
-------------------------;
END;
NOTE: Exception raised in exception section cannot be handled in the same block exceptional section. But
possible to handle outer bock exceptional sections which is also called as EXCEPTION PROPAGATION
CASE: 8
DECLARE
---------------
BEGIN
DECLARE
V NUMBER (2):=12345
BEGIN
----------------
EXCEPTION
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
TRACING AN EXCEPTION
DECLARE
BEGIN
SELECT...................................;
SELECT...................................;
SELECT...................................;
SELECT...................................;
SELECT...................................;
SELECT...................................;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-------------------------------------------------;
END;
NOTE: In above case we are not able to identify in which select statement the exception has occurred. so to
overcome this situation we writ as follows
DECLARE
----------------- ;
BEGIN
DBMS_OUTPUT.PUT_LINE('H');
SELECT............................................;
DBMS_OUTPUT.PUT_LINE('A');
SELECT............................................;
DBMS_OUTPUT.PUT_LINE('R');
SELECT............................................;
DBMS_OUTPUT.PUT_LINE('I');
SELECT............................................;
DBMS_OUTPUT.PUT_LINE('S');
SELECT............................................
DBMS_OUTPUT.PUT_LINE ('H');
EXCEPTION
WHEN NO_DATA_FOUND THEN
END;
NOTE:
If we get only 'H' as output then in first select statement the exception has occurred.
If we get 'H','A' as output then in second select statement the exception has occurred.
If we get 'H' ,'A','R' as output then in third select statement the exception has occurred.
If we get 'H' ,'A','R','I' as output then in fourth select statement the exception has occurred.
If we get 'H' ,'A','R' ,I','S' as output then in third select statement the exception has occurred.
If we get 'H' ,'A','R','S',H' as output then there are no error in select statements.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Procedure:-
It is program unit (or) PL/SQL block which takes the parameters.
In the procedure we attach header to the PL/SQL block.
Procedure is a program unit which is used to execute statements.
It acts as procedural statements and we use it for statements executions (more often).
It is a stored program unit.
A procedure has to be four sections:-
They are:
1) Header section
2) Declarative section
3) Execution section
4) Exception section
Syntax:-create [or replace] procedure <procedure_name> (Para)[authid_user definer/current_user] is
begin
-----------------------
Exception
-----------------------
End [procedure name];
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Note: -In the above syntax “is” represents standard alone procedure.
Calling procedure:-
SQL/Plus
SQL developer(new tool)
Blocks
Unix
Front end applications(apps)
Web applications
Parameters:-
Basically parameters of 3 types ate:
1. IN (read)
2. OUT (write)
3. INOUT (read and write)
procedure created
Desc p;
Procedure p
Calling in SQL*plus:-
Exec p;
Calling in blocks:-
begin
P;
end;
SQl*Plus:-
Calling environment:
Var a number;
We will declare this variable in executable section.
Exec:a:=1000;
Here assigning value to variable(a), from this variable(a) to I am sending value to’X’.
Exec p(:a);
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
declare
a number:=&n;(calling in blocks)
begin
p(a); (this is calling environment)
end;
Note:-
x number;
x In number
above both two statements are same and ‘In’ is default parameter.
Declare
vname varchar2(10):=&n;
a number(5);
begin
select sal into a from emp where ename=vname;
p(a);
end;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
SQL/Plus:-
var a number;
var b varchar2(10);
exec :a:=7839;
exec p(:a,:b);
print b;
exec DOCL(:b);
blocks:-
declare
a number(5):=7839;
b varchar2(10);
begin
p(a,b);
DOCL(b);
end;
Spool concept:-
Sql>spool c:/gv.sql;
>select * from emp;
Sql>spool off;
Sql>spool c:/gv.sql append ; (it will append to previous one)
SQL * Plus:-
var a number;
exec :a:=7788;
exec p(:a);
print a;
Blocks:-
declare
a number(5):=&n;
begin
p(a);
DBMS_OUTPUT.PUT_LINE(a);
End;
While creating time we will declare (arguments/parameters eg: X in number) we will call that as “formal
parameters”.
EX: exec p(:a,:b) these are “actual parameters”.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
2. Named notation; (by using names (formal parameters) we can implies the value)
3. Mixed notation.
Mixed notation:-
Note:-In mixed notation, named notation has to follow positional `
notation.P(100,200,Z=>300);
P(100,Y=>200,300);
P(100,Y=>300,X=>400,Z=>200);
In the above statements first will be valid remaining are in-valid because here we are assigning values in two
times to ‘X’.
values get referred from actual to formal and formal to actual in two methods they are:
i. Reference method; (enhances performance).
ii. Copy method; (or) (pass by value method).
By default ‘In’ parameter takes the values through reference method which is faster than the copy method
and desirable, where as in the case of out and in out parameters values get passed through copy method.
Which degrades
the performance, so to avoid this thing we have a reserved word called ‘No Copy’ which is introduced from
9i onwards.
No copy:-
we mention No Copy for Out and InOut parameters so, to take the values through reference method (which
in turn) accelerates/alters the performance.
Note:-Mentioning NOCOPY to the ‘IN’ parameters throws an error.
Eg:- Create or replace procedure p(X number, Y out nocopy number) is
Begin
Y:=X+1000;
End p;
Note:- Here ‘nocopy’ is reserved word or key word.
SQL*Plus:-
Var a number;
Var b number;
Exec :a:=100;
Exec p(:a, :b);
Print b;
Once we pass the value to ‘In’ parameter throughout the program we can’t vary the value.
Note:- Always ‘In’ parameters should not be at left side of assignment operator which means ‘In’ parameters
acts as a ‘constant’ in the scope of program.
Create or replace procedure p(X in number, Y out number) is
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Begin
X:=200;
Y:=X+100;
End;
Exec p(100,:b)
Local subprograms:-
They are procedures/functions which are defined in the declarative section named and unnamed blocks.
We have to call these local programs within the scope of that block.
It won’t get stored anywhere else on by themselves.
Declare
Procedure p is
Begin local sub programs
DOCL(‘hello’);
End p;
Begin p;
End; Here we won’t mention create/replace.
Forward declaration:-
Basically if you want to call a program it has to be get defined very previously.
Whenever you call a program before defining throws an error.
For mutual exchange purpose sometimes we have a need to call a procedure before defining.
To fulfill this requirement we will declare the procedure very previously which is calling before defining.
If you want to call a procedure before defining you have to declare those procedures vary previously.
Declare
V number (5):=5;
Procedure p2(Y inout number); --forward declaration
Procedure p1(X inout number) is
Begin
If X>0 then
Docl(X);
X:=X-1;
P2(X);--calling
End if;
End p1;
Procedure p2(Y inout number) is --defining
Begin
P1(Y);
End p2;
Begin
P2(v); -- calling and executable section first compiler comes here.
First define then call any procedure without defining if
you need to make a call at least we need to declare.
End;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End p3;
Exec p3;
Note:-
A procedure can optionally contain ‘return’ statement but it won’t through any value as in the given eg.
Create or replace procedure p3 is
V number(5):=100;
Begin
DOCL(v);
Return v;
DBMS_OUTPUT.PUT_LINE(v);
End p3;
Functions
They are the PL/SQL program units which allow parameters similar to that of procedures.
But unlike procedures they return value by default.
Functions are useful for calculation purpose and for data manipulation purpose (DML).
Functions makes the queries simple, readable and also enhance the performance.
Note:- Providing out and inout parameters’ in functions is not preferable.
Calling functions:-
1. SQL/Plus
2. Blocks
3. SQl Developer
4. Apps
5. Select statement
6. Objects
block:-
declare
a number(5);
begin
a:= fun;
DBMS_OUTPUT.PUT_LINE(a);
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End;
SQL/Plus:-
Var a number;
Exec :a:=fun; --where ‘a’ holds the value
Print a;
Create or replace procedure p is
B number(5);
Begin
B:=fun;
DBMS_OUTPUT.PUT_LINE(b);
End p;
Create or replace function f1 return number is
Begin
Return fun;
End f1;
Select fun from dual;
Note:- In the return statement we can mention value directly, expression, another function, cursor variables,
index by table (collection), Boolean value, and so on…..
SQL/Plus:-
Var a carchar2(10);
Var b number;
Exec :b:=7788;
Exec :a:=fin(:b);
Print a;
Blocks:-
Declare
A varchar2(10);
B number(5):=&n;
Begin
A:=fin(b);
DBMS_OUTPUT.PUT_LINE(a);
End;
Select fin(empno) from emp;
Create or replace function fn(X varchar2) return number is Vno number(5);
Begin
Select empno into vno from emp where ename=X;
Return vno;
End fn;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
SQL*Plus:-
var a number;
var b number;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
exec :a:=f(:b);
print a;
100
Print b;
600
Blocks:-
Declare
A nmber(5);
B number(5);
Begin
A:=f(b);
DBMS_OUTPUT.PUT_LINE(a||’ ‘||b);
End;
SQL> select f(:b) from dual;
Note: It is not possible to call the function which are having out and in out parameters in ‘select statement’.
Using functions:-
We can use the functions in the following areas
i. Where clause
ii. Start with
iii. Connect by
iv. Having
v. Group by
vi. Order by
vii. Select
viii. Update set clause
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Restrictions of function:-
Functions
Select statement DML statements
Commit
DML
DML Rollback to save
point
Select
Selec Alter system
t
Alter session
In the above diagram select statements DML is not possibls and select is possible.
In the DML statements DML will not possible on same function table. But it will possible on different function
tables.
In DML statements select possible on different (or) same function table.
NOTE:-
We can use select statement in DML operations.
Using DML operations in select statements is not passible either directly (or) indirectly.
Functions/procedures i.e DML
Select f (DML) from dual;
Select f (select) --invalid
Update t1 set val=f(DML(T1)) --invalid
Update t2 set val =f(DML(T2)) --valid
Generally SQL statements won’t allow us to call the functions which are having DML operations. If you do
so, resulting into error. If you won’t to restrict the user not to provide DML operations in a function which are
frequently used in select statements, we need to provide “program restrict reference” while creating a
function, in this manner we will eliminate the impurities.
Create or replace function f return number is
Begin
Null;
End f;
Note:-
We can define a function without return statement but at the time of calling it throws error as such in above
eg.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Var a number;
Exec :a:=f; --throws an error.
Functions:-
By default function returns single value.
It is possible to call in SQL statements.
For calculations (or) computing purpose.
Using functions in select statement will enhance the performance and simplifies the coding.
Forward declaration:-
Basically if you want to call a program it has to be get defined very previously.
Whenever you call a program before defining throws an error.
For mutual exchange purpose sometimes we have a need to call a procedure before defining.
To fulfill this requirement we will declare the procedure very previously which is calling before defining.
If you want to call a procedure before defining you have to declare those procedures vary previously.
Declare
V number (5):=5;
Procedure p2(Y input number); --forward declaration
Procedure p1(X input number) is
Begin
If X>0 then
Docl(X)
X: =X-1;
P2(X); --calling
End if;
End p1;
Procedure p2(Y input number) is --defining
Begin
P1(Y);
End p2;
Begin
P2 (v); -- calling and executable section first compiler comes here.
First define then call any procedure without defining if You need to make a call at least we need to declare.
End;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
DOCL(v);
Return v;
DBMS_OUTPUT.PUT_LINE(v);
End p3;
Functions:-
By default function returns single value.
It is possible to call in SQL statements.
For calculations (or) computing purpose.
Using functions in select statement will enhance the performance and simplifies the coding.
Packages:-
It is a container/program unit area which is useful to store related things at one place.
It provides modularity, scalability, encapsulation, data security, portability, code analysation, debugging the
code, tracing the code, profiling the code, location monitoring and so on…
Alters/decreases the redundancy.
Note:-
Packages won’t allow parameters, nesting, and calling.
Package specification:-
It is a prototype for package body program.
In specification we declare variables, cursors, exceptions, procedures, functions and so on…
This is for information purpose.
It can exist without body.
Declaring cursor variables is not possible; defining ref cursor data type is possible.
A package body can’t exist without package specification but reverse is not so…
Package specification and body stores in different memory areas.
PL /SQL objects defined in package specifications are considered as global objects, won’t allow coding part.
Package body:-
It consists of program coding.
A package body can optionally has executable section.
Variables and programs which are defined in package body without specifying I package specification are
called as local variables, local programs.
We can drop a package body without dropping package specification
Package specification drops.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End packagename;
Pragmaautonomytransaction (Tx):-
It is an independent Tx happens individually irrespective of parent Tx.
Limitations:-
Package specification won’t allow pragma; we can apply for packeged procedures and packages.
Create or replace procedure p is pragma autonomius_transaction;
Begin
Insert into nestab values(10);
End p;
Create table nestab(sno number(5));
Select * form nestab;
Calling environment:
Begin
Insert into nestab values(11);
P;
Insert into nestab values(12);
Rollback;
End;
Output: 10
While using pragma autonomus Tx we need to mention commit, rollback as mandatory.
DDl- autocommit commands
DML- non-autocommit.
Create or replace procedure p is pragma autonomius_transaction;
Begin
Insert into nestab values(10);
Rollback;
End p;
Begin
Insert into nestab values(11);
P;
Insert into nestab values(12);
Commit;
End;
Select * from nestab;
Out put:-
11
10
12
Create or replace procedure p is
Begin insert into nestab values(10);
Rollback;
End p;
Begin insert into nestab values(11);
P;
Insert into nestab values(12);
Commit;’
End p;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Out put:
12
Note:-We avoiding mutating error using pragma.atonomous_transaction.
Deff:
In lining a program means replacing the procedure call with actual executable code copy of a program.
Note:-
Programs which are having static code and frequently used programs (or) subject to the pragma
inline(preferrable).
Syntax:-
Pragma inline(‘procedure name’,{‘yes/no’});
Declare
Stime integer;
Etime integer;
V number;
Function f(x number) return number is
Begin
Return x;
End f;
Begin
Pragma inline(‘f’,’yes’);
Stime :=dbms_utility.get_time;
For I in 1..10000 loop
V:=f(i);
End loop;
Etime:=dbms_utility.get_time;
DBMS_OUTPUT.PUT_LINE(etime-stime);
Pragma inline(‘f’,’no’);
Stime:=dbms_utility.get_time;
For I in 1..10000 loop
V:=f(i);
End loop;
Etime:=dbms_utility.get_time;
DBMS_OUTPUT.PUT_LINE(etime-stime);
End;
Packages:-
It is a container/program unit area which is useful to store related things at one place.
It provides modularity, scalability, encapsulation, data security, portability, code analysation, debugging the
code, tracing the code, profiling the code, location monitoring and so on…
Alters/decreases the redundancy.
Note:-
Packages won’t allow parameters, nesting, and calling.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Package specification:-
It is a prototype for package body program.
In specification we declare variables, cursors, exceptions, procedures, functions and so on…
This is for information purpose.
It can exist without body.
Declaring cursor variables is not possible; defining ref cursor data type is possible.
A package body can’t exist without package specification but reverse is not so…
Package specification and body stores in different memory areas.
PL /SQL objects defined in package specifications are considered as global objects, won’t allow coding part.
Package body:-
It consists of program coding.
A package body can optionally has executable section.
Variables and programs which are defined in package body without specifying I package specification are
called as local variables, local programs.
We can drop a package body without dropping package specification
Package specification drops.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Eg:
Crate or replace package pack is v number(5):=400;
Ex exception ;
Cursor c is select * from emp;
Procedure p(X inout number);
Function f(y in out number);
Return number;
End pack;
Create or replace package body pack is L number(5):=500;
Function lf(Z in number )return number is lv number(5);
Begin
Lv:=Z+L;
Return lv;
End lf;
Procedure p (X inout number)is pv number(5);
Begin
Pv:=2000+lf(X);
X:=pv+5000;
End p;
Function f(Y inout number)return number is
Begin
Y:=Y+lf(v);
V:=Y+L;
Return v;
End f;
If you want to define package body first we need to define package specification.
SQL*PLUS:
SQL>var a number;
Exec :a:=1000;
Exec pack.p(:a);
Print a;
BLOCKS:
Declare
a number(5):=2000;
begin
pack.p(a);
DBMS_OUTPUT.PUT_LINE(a);
End;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
FUNCTIONS:
SQL*PLUS
Var a number;
Var b number;
Exec :b:=4000;
Exec :a:=pack.f(:b);
BLOCKS:
Declare
A number(5);
B number(5):=1000;
Begin
A:=pack.f(:b);
DBMS_OUTPUT.PUT_LINE(a||’ ‘||b);
End;
NOTE:-
If you won’t close the packaged (pack’s) cursor in any program then that is last for entire session.
We can call the packaged procedures and functions outside of package which are specified in package
specification(global accessing).
Attempting to call packaged local sub programs to call outside of package throws an error.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Create or replace package body pack is Procedure p(X rec)is vrow emp%rowtype;
Begin
Loop
Fetch X into vrow ;
DBMS_OUTPUT.PUT_LINE(vrow.ename);
Exit when X%not found;
End loop;
End p;
End pack;
BLOCK:
Declare
Type recl is ref cursor;
Vrec recl;
Begin
Open vrec for select * from emp;
Pack.p(vrec); --calling
End;
Note: Defining cursor variable in package specification will not be allowed but defining ref cursor is possible.
Packaged Cursors:
Create or replace package pack is cursor c return emp%rowtype is select * from emp;
End pack;
Here we are defining ‘cursor’ in package specification we can use this anywhere.
Begin
For i in pack.c
Loop
DBMS_OUTPUT.PUT_LINE(i.ename);
End loop ;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End;
We can hide the cursor select statement through package concept as shown in the snippent:
Create or replace package pack is cursor c return emp%rowtype ;
End pack;
Create or replace package body pack is cursor c return emp%rowtype is select * from emp;
End pack;
Begin
For i in pack.c
Loop
DBMS_OUTPUT.PUT_LINE(i.ename);
End loop ;
End;
Out Put:
Emp 14 records
A package body can optionally contain executable section. Which is one time initialization but it should be at
last in the package body if we have any sub programs.
Create or replace package pack is v number (5);
End pack;
Create or replace package body pack is
Begin
V: =5000;
End pack;
Note:-
We can also call the packaged function in select statement but that should not contain out and inout
parameter.
Drop package <package_name>
Here along with package specification, body alo will drop.
Dropping packaged body without dropping package specification
Drop package body pack;
Polymorphism(overloading):-
Defining multiple local subprograms with the very same name but by differing number, order and data types
of parameters.
Create or replace package pack is Procedure p(x number);
Procedure p (x number, y number);
Procedure P(x number, y varchar2);
Procedure p(y varchar2, x number);
End pack;
Note:-The data types should not be same family while comparing to procedures.
Creating or replace package body pack is procedure p(x number) is
Begin
DBMS_OUTPUT.PUT_LINE(x);
End p;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End p;
Procedure p(x number, y varchar2) is
Begin DBMS_OUTPUT.PUT_LINE(x||’ ‘||y);
End p;
Procedure p(y varchar2, x number)is
Begin
DBMS_OUTPUT.PUT_LINE(y||’ ‘||x);
End p;
End;
Calling environment:-
SQL>exec p(100);
SQL>exec p(‘a’,200);
SQL>exec p(200,’a’);
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
L_r:=l_r+f(i); --calling
End loop;
Edate:=dbms_utility.get_time;
DBMS_OUTPUT.PUT_LINE(edate_sdate);
End;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Note: Internally it takes one virtual variable and it checks v number NOT NULL(it is not preferable more time
it will take if you use coading in program it is better like if v is not null).
Same as above program but variable using without NOTNULL.
Output:
Time: 44
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
V:=v+1;
DBMS_OUTPUT.PUT_LINE(v);
End;
Out put:
2147483647
-2147483648
Pragmaautonomoustransaction (Tx):-
It is an independent Tx happens individually irrespective of parent Tx.
Limitations:-
Package specification won’t allow pragma; we can apply for packeged procedures and packages.
Create or replace procedure p is pragma autonomous_transaction;
Begin
Insert into nestab values(10);
End p;
Create table nestab(sno number(5));
Select * form nestab;
Calling environment:
Begin
Insert into nstab values(11);
P;
Insert into nestab values(12);
Rollback;
End;
Output: 10
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Deff: Inlining a program means replacing the procedure call with actual executable code copy of a program.
Note: Programs which are having static code and frequently used programs (or) subject to the pragma
inline(preferrable).
Syntax:
Pragma inline(‘procedure name’,{‘yes/no’});
Declare
Stime integer;
Etime integer;
V number;
Function f(x number) return number is
Begin
Return x;
End f;
Begin
Pragma inline(‘f’,’yes’);
Stime :=dbms_utility.get_time;
For I in 1..10000 loop
V:=f(i);
End loop;
Etime:=dbms_utility.get_time;
DBMS_OUTPUT.PUT_LINE(etime-stime);
Pragma inline(‘f’,’no’);
Stime:=dbms_utility.get_time;
For I in 1..10000 loop
V:=f(i);
End loop;
Etime:=dbms_utility.get_time;
DBMS_OUTPUT.PUT_LINE(etime-stime);
End;
LOB datatype:
Before of 8i if you want to store the images or huge information we opt(choose) for long datatypes but , we
have so many restrictions on long datatypes to overcome this disadvantage we have LOB datatype.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
CLOB
NCLOB
External
Bfiles
CLOB: allows huge information upto 4GB from 11g onwords even it supports 8 to 128TB.
BLOB: stores binary data, allows images, audio,video files and so on…
NCLOB: it stores national database chracterset data. Supports multi languages.
Bfiles: useful to store files in the form of binary data.
Commit and rollback is not passible to provide on this data.
abc 01010
File not store in db
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Dbms_lob.close(vclob);
DBMS_OUTPUT.PUT_LINE(rdata);
End;
Declare
Bimage bfile:=bfilename(‘DY’,’gimage.bmp’);
Image_loc bfile;
Max_data integer:=60;
Offset_integer:=1;
Raw_data raw(100);
Begin
Delete from imagetab;
Insert into imagetab values(10,bimage);
Select image into image_loc from imagetab;
Dbms_lob.open(image_loc);
Dbms_lob.read(image_loc, max_data, offset,raw_data);
Dbms_lob.close(image_loc);
DBMS_OUTPUT.PUT_LINE(rawtohex(raw_data));
DBMS_OUTPUT.PUT_LINE(utl_raw.cast_to_varchar2(raw_data));
End;
Declare
Vdir bfile:=bfilenamme(‘DY’,’gv.txt’);
Colfile clob;
Max_data integer:=10;
Des_offset integer:=1;
S_ofset integer:=1;
Lang_ctx integer:=dbms_lob.default_lang_ctx;
War_mes integer;
Begin
Delete from direction;
Insert into direction values(10, empty_clob);
Selection dcol into colfile from direction;
Dbms_lob.open(colfile,dbms_lob,lob_readwrite);
Dbms_lob.open(vdir);Dbms_lob.load clob from file(colfile, vdir, dbms_lob.maxsize,
des_offset, s_offset, nls_charset_id(‘USTASCII’), lang_ctx, war_mes);
Dbms_lob.close(colfile);
Dbms_lob.close(vdir);
End;
Triggers:-
They are the stored programs fires implicitly unlike subprograms.
Triggers fires automatically when event occurs.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
We can’t call trigger and pass parameters and can’t nest (trigger with in trigger).
Usages:-
Data auditing
Enforcing the referential integrity
Security
Data replication
Application monitoring(AM)
Enforcing the data
Triggers have their own name space.
Triggers won’t allow commit and rollback, but by using “pragma atonomous transaction we can mention
commit and rollback in triggers.
Basically triggers are of two types
1.Application trigger
2.Database triggers
Database triggers:-
1. DML triggers (table)
2. Instead of trigger(views)
3. DDL trigger(schema) -- 3 and 4 never write these in DBA level.
4. DB trigger(database)
5. Compound trigger(11g)(table)
We will write triggers on tables, views, schema and database.
DML triggers:-
We provide DML triggere on table
Based on DML events execution of trigger takes place implicitly.
This triggers are again of two types:
1.) statement level trigger (or) table level trigger
2.) row level trigger
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
If further provides the additional restriction on trigger execution.in trigger conditon should always be a
boolean expression statement level trigger won’t allow trigger condition.
(4)-trigger body:-
It specifies what action we have to perform through trigger.
Rowlevel trigger:
It will make use of pseudo records as shown in following table.
Virtual table:
old new
insert null
update
delete null
Here we wil represent new and old in this program i.e rowlevel trigger program.
Write a rowlevel trigger to update the salaries witch one specific value for an increment, if Any one of the
existing salaries is greater than new salaries then I have to cancel all the transactions happened by trigger.
Create or replace trigger ustrig before update on emp1;
For each row
Begin
If :old.sal>:new.sal then
Raise_application_error(-20003,’sal cannot be decremented’);
Else
DBMS_OUTPUT.PUT_LINE(‘icremented’);end if;
End;
From the trigger if we get any error, all the previous transactions will get cancelled.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
When condition skips the execution of trigger body when ‘when condition’ becomes ‘false’.(but insertion
takes place).
If when condition becomes true then allows trigger body to execute.
Create or replace trigger logtrig before insert or update or delete on logtab;
For each row
when(to_char(sysdate,’HH’)not between ‘05’ and ‘08’)
begin
DBMS_OUTPUT.PUT_LINE(‘login time’);
End;
Insert into logtab values(10);
1 row created.
Create table logtab(sno number(5));
DDL triggers:-
Syntax:
Create or replace trigger <trigger_name> before/after DDL on schema
Begin
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
……….
Exception
…………
End [trigger_name]
DDL attributes:_
In DDL we have more than 100 attributes but here we will go for
Ora_sysevent
Ora_DICT_obj_name
Ora_DICT_obj_type
We will provide DDL commands on schema, mainly for auditing purpose.
Create trigger audtrig before create or drop on schema
Begin
Insert into audtab values (user, ora_sysevent, ora_dict_obj_name, ora_dict_obj_type, sysdate);
End audtrig;
Create table audtab(suser varchar2(10), sevent varchar2(10), sname varchar2(10), stype varchar2(10), sdate
date);
Create table SAM(sno number(5));
Select * from audtab;
Suser Sevent Sname Stype Sdate
Apps Create Sam Table 11-mar-13
Drop table sam;
Select * from audtab;
Before Log on
After(T)
Befor(T) Log off
After
Before(T) Shutdown
After
Servererror
errornumber
before Startup
After(T)
Attaching the procedure to the trigger in the place of trigger body with ‘call statement’, so to reduce the
redundancy as in the following eg.
Create or replace procedure p is
Begin
DBMS_OUTPUT.PUT_LINE(‘hello’);
End;
Create table RAM(sno number(5));
Create or replace trigger protrig before insert on RAM
Call p(don’t use semicolon here, if you use you will get error)
/
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
-trigger created.
Insert into RAM values(10);
Hello
-1 row created.
Disable(11g):-
Prior to 11g we only have an option to disable an existing trigger fron 11g onwords we can disable a trigger
while creating/defining.
Create or replace trigger disable before insert on RAM disable
Begin
DBMS_OUTPUT.PUT_LINE(‘this is disable trigger’);
End disable;
Insert into RAM values(10);
-1 row created.
To enable/disable the trigger we’ve to make use of ALTER.
Alter trigger distrig enable;
Insert into RAM values(10); --this is disable trigger.
-1 row created.
We can define max of 12 triggers on a table(DML).
We can write a trigger to fire when updating on specific column:-
Create table uptab(sno number(5), loc varchar2(10));
Create trigger updating before updating of sno on uptab
Begin
DBMS_OUTPUT.PUT_LINE(‘updating on column’);
End;
Insert into uptabvalues(10, ‘x’);
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
User_dependences:-
To find out reflection (or) information between referenced and dependent object we use this table.
Note:It won’t give information regarding remote dependenies for that we have to run a script file so to create
one procedure and two tables. here deptree and ideptree are remote dependencies.
Dbms_metadata:-
To create DDL report for an object.(dbms_utility.get_ddl(emp))
PL/scope tool(11g):-
It is an utility, to get the information of identifier activites.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Note:
Here while creating policy functions(p_schema and p_object) these 2 in parameters are mandatory. ‘1=2’ this
condition will append to select statement dynamically.
SQL/Plus:-
Var a varchar2(10);
Exec :a:=pot_fun(‘apps’,’emp’);
Print a;
Exec dbms_rls.add_policy(‘apps’,’emp1’,’res’,’appa’,’pol_fun’,select,insert,update’);
Select * from emp1;
Exec.dbms_rls.drop_policy(‘apps’,’emp1’,’res’);
Note:-
If you create next time with the very same name also same will be applicable.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
DBMS_OUTPUT.PUT_LINE(‘vnes next’||vnes.next(2));
DBMS_OUTPUT.PUT_LINE(‘vnes values’);
For I in vnes.first..vnes.last loop
DBMS_OUTPUT.PUT_LINE(‘vnes values(‘||I||’)’||vnes(I));
End loop;
if vnes.exists(2) then
dbms_output.put_line(‘vnes second value exists’||vnes(2));
dbms_output.put_line(‘vnes second value doesnot exists’);
end if;
vnes.extend;
vnes.exted(2);
DBMS_OUTPUT.PUT_LINE(‘vnes value after extension’);
For I in vnes.first..vnes.last loop
DBMS_OUTPUT.PUT_LINE(‘vnes values(‘||I||’)’||vnes(I));
End loop;
Vnes(5):=‘E’;
Vnes(6):=‘F’;
Vnes(7):=‘G’;
Vnes.extend(2,3);
DBMS_OUTPUT.PUT_LINE(‘nes value after providing element’);
For I in vnes.first..vnes.last loop
DBMS_OUTPUT.PUT_LINE(‘vnes values(‘||I||’)|| vnes(I));
End loop;
vnes.trim;
vnes.trim(2);
DBMS_OUTPUT.PUT_LINE(‘vnes values after trim’);
For I in vnes.first..vnes.last loop
DBMS_OUTPUT.PUT_LINE(‘vnes values(‘||I||’)’||vnes(I));
End loop;
vnes.delete(1);
vnes.delete(2,5);
DBMS_OUTPUT.PUT_LINE(‘vnes values after specific deletion’);
For I in vnes.first..vnes.last loop
DBMS_OUTPUT.PUT_LINE(‘vnes values(‘||I||’)’||vnes(I));
End loop;
Vnes.delete;
DBMS_OUTPUT.PUT_LINE(‘vnes values after complete deletion’);
End;
collection variable should not be ‘NULL’, to avoid that in that case we will define elements.
The function should be empty nes()(or)nes(‘A’,’B’,’C”,’D’);
Usage of collections:-
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
1 A
3 C
5 C
densely
1 A
2 B
3 C
4 C
5 D
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Declare
Type nes is table of varchar2(10) index by pls_integer;
Vnes nes:=nes();
Begin
Null;
End;
Error:no function name ‘nes’ exists in this scope.
INLINE
Bulk bind:-
Concept of bulk bind is a mechanism which is used to enhance the performance drastically, by decreasing the
context switches.
Bulk bind reduces the interaction between SQLand PL/SQL engine.
We will maintain the bulk bind data through collections.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Open c;
Sdate:=dbms_utility.get_time;
Loop
Vnes.extend;
Fetch c into vnes(vnes.last);
Exit when c%not found;
End loop;
Close c;
Edate:=dbms_utility.get_time;
DBMS_OUTPUT.PUT_LINE(edate-sdate);
Open c;
Sdate:=dbms_utility.get_time;
Fetch c bulk collect into vnes;
Edate:=dbms_utility.get_time;
Close c;
DBMS_OUTPUT.PUT_LINE(edate-sdate);
End;
Collections:-
Note:-We won’t initialize the ‘index by table’ datatype variable with a constructor (or) function trying to do so
through an error.
Eg:-
Declare
Type nes is table of varchar2(10);
Vnes nes:=nes(‘a’,’b’,’c’);
Begin
Vnes.delete(2)
DBMS_OUTPUT.PUT_LINE(‘vnes first’||vnes.first);
DBMS_OUTPUT.PUT_LINE(‘vnes last’||vnes.last);
DBMS_OUTPUT.PUT_LINE(‘vnes prior’||vnes.prior(3));
DBMS_OUTPUT.PUT_LINE(‘vnes next’||vnes.next(1));
DBMS_OUTPUT.PUT_LINE(‘vnes count’||vnes.count);
If vnes.exists(2) then
DBMS_OUTPUT.PUT_LINE(‘vnes second value exists’||vnes(2)); -- not existed
End if;
Vnes.extend;
If vnes.existts(4) then
DBMS_OUTPUT.PUT_LINE(‘vnes fourth value exists’||vnes(4));
Else
DBMS_OUTPUT.PUT_LINE(‘vnes fourth does not exists’);
End if;
End;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
End loop;
End p;
Begin
p(vnes);
end;
vnes :=nes(‘a’,’b’,’c’,’d’);
Y nes:=nes();
Function fun(x nes) return nes is
Begin
Return x; --here we are returning also
End fun;
Begin
Y:=fun(vnes);
For I in Y.first..Y.last loop
DBMS_OUTPUT.PUT_LINE(Y(i));
End loop;
End;
Note:-
From 11g onwards for all statement allows merge command
DECLARE
TYPE nes IS TABLE OF NUMBER;
Output:-
Elapsed time 198
5
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
A
C
C
Table function:-
It is a function which acts as same to that of table to SQL engine with the help of table operator called ‘table’.
We provide table function in from clause of a select statement.
SQL engine can’t identify it as a function.
Note:-
Table functions have to always return data from collections only.
But we can’t provide functions in from clause.
Eg:-
Create or replace function colfun return nes is
Vnes nes:=nes(‘a’,’b’,’c’,’d’,’e’,’f’)
Begin
Return vnes; -- here vnes always collection.
End;
Select * from table(col_fun);
Column_val -- it internally pseudo column generates, introduced from 10g
A
B
C
D
E
F
Table function data will be displayed under a column name called column_val which is a pseudo column.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
1. Execute immediate(statement).
2. DBMS_SQL(packages)
Note:-Dynamic SQL statement falls pray, to SQL injections. We can also execute immediate to execute DDL
statements in the program which is normally not possible.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Calling environment:-
SQL>exec p(‘ ‘ ‘king’ ‘ ‘);
King 10
Exec p(‘null union select ename, sal from emp’);
Here we have a chance for attacking malicious data so, to restrict the SQL injection convert the dynamic SQL
into static as shown in following eg.
LOOP
FETCH vrec INTO v_name, v_deptno;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Exec p(‘king’);
King 10
Exec p(‘null union select ename,sal from emp); (here getting unintended data is not possible).
Note:-
When we know all the SQl identifiers (column, table names) before of fraiming a statement, in that case only
it is possible to convert the dynamic SQL statements into static SQl which means it is not possible to convert
all the dynamic SQL statements static if this is the case then mien/mise the attacking of SQL injection by
using “bind argument” as shown in the following snippet (or) eg.
In addition with protectiong the PL/SQL code from SQL injection it also possible to enhance the performance
immeyely(more effectively).
Using bind arguments in dynamic SQL will avoid hard parsing(buffer myss) and promote soft parsing(buffer
hit).
For the above eg just change
Begin
Open vrec for ‘select enaame, deptno from emp where ename=:’ using x_name;
Loop
-- remaining structure is same.
Exec p(‘king’);
Exec p(‘null union select ename,sal from emp’);
Finally we will reduce the SQL injection by sanitizing the user inputs with the help of an APL i.e
DBMS_assert(package).
While tunning the PL/SQL code avoid implicit conversion which ia a burden to the ename as server as such
in the following.
Eg:-
DECLARE
Stime NUMBER := 0;
Etime NUMBER := 0;
V VARCHAR2 (10);
BEGIN
Stime := DBMS_UTILITY.get_time;
FOR I IN 1 .. 1000
LOOP
V := I;
END LOOP;
Etime := DBMS_UTILITY.get_time;
DBMS_OUTPUT.PUT_LINE (edate_sdate);
END;
DECLARE
Stime NUMBER := 0;
Etime NUMBER := 0;
V NUMBER (5);
BEGIN
Stime := DBMS_UTILITY.get_time;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
FOR I IN 1 .. 1000
LOOP
V := i;
END LOOP;
Ctime := DBMS_UTILITY.get_time;
DBMS_OUTPUT.PUT_LINE (edate - sdate);
END;
cursor eg:-
DECLARE
CURSOR c
IS
SELECT * FROM emp;
--here select stmt get executes and opens the memory area and gets data.
LOOP
FETCH c INTO vrow; --here fetching will happen.
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
DBMS_OUTPUT.PUT_LINE (vrow.ename);
IF c%NOTFOUND
THEN --(1)
EXIT;
END IF;
END LOOP;
CLOSE C;
END;
If you write like this we can stop the program after 3rd record. In this case for loop is not prefereable, simple
loop is prefereable.
Paramatarised cursor eg:-
Declare
Cursor c(x number) is select * from emp where deptno:=x;
Vrow emp%rowtype;
Vno number(5):=&n;
Vnol number(5):=&m;
Begin
Open c(vno);
Loop
Fetch c into vrow;
DBMS_OUTPUT.PUT_LINE(vrow.ename)
Exit when c%not found;
End loop;
Close c;
Open c(vnol);
Loop
Fetch c into vrow;
DBMS_OUTPUT.PUT_LINE(vrow.ename);
Exit when c%not found;
End loop;
Close c;
Before ‘open c’:
% is open -F
% found –E
% notfound -E
% rowcount -E
After ‘open c’:
% is open -T
% found -T
% notfound -F
% rowcount -0
After fetch: (1st fetch)
% is open -T
% found -1
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
% notfound -F
% rowcount -1
After close c:
% is open -F
% found -E
% notfound -E
% rowcount -E
We can use cursor variable as a parameter in stored procedures
RETURN TRUE;
END f;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
DECLARE
Vrec1 SYS_REFCURSOR;
V BOOLEAN;
Vrow emp%ROWTYPE;
BEGIN
V := f (vrec1);
LOOP
FETCH vrec1 INTO vrow;
DBMS_OUTPUT.PUT_LINE (vrow.ename);
EXIT WHEN vrec1%not found;
End loop;
End;
Vrec sys_refcursor;
DECLARE
Vrec1 SYS_REFCURSOR;
BEGIN
OPEN vrec FOR SELECT * FROM emp;
Vrec1 := vrec;
CLOSE vrec;
DECLARE
Vrec2 SYS_REFCURSOR;
Vrow emp%ROWTYPE;
BEGIN
Vrec2 := f;
LOOP
FETCH vrec2 INTO vrow;
DBMS_OUTPUT.PUT_LINE (vrow.ename);
EXIT WHEN vrec2%NOTFOUND;
END LOOP;
END;
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Lienumber Object
3 Procedure APPs-p
3 Procedure
3 Procedure apps.p2
2 Anonymous block
Note:-
RAJU CHINTHAPATLA
Oracle PL/SQL Training Document Raju Ch
Instead of trigger:-
This trigger is for views, to perform DML operations on complex views will not be allowed directly, but by
using instead of trigger it is passible.
This trigger is always a rowlevel trigger even if you won’t mention the “for each row” clause.
Defining instead of trigger on tables ends with an error.
Create table vtabl(sno number(5));
Create table vtab2(loc varchar2(10);
Create view comview as select * from vtab1, vtab2;
Insert into comview values(10,’hyd’);
Error:
Can not modify a column which maps to a non key preserved data.
Create or replace triggr comtrig
Instead of insert on comview;
Begin
Insert into vtab1 values(:new.sno);
Insert into vtab2 values(:new.loc);
End;
Insert into comview values(10,’hyd’);--here insertion is successfully happening on view.
Note:-DML operation can’t perform on complex views. But as in the above case trigger is inserting the values
before insertion.
Mutating error:-
We get this error when a row level trigger attempts to read or write the table from which it was raised.
You won’t get this error in statement level.
Create or replace trigger muttrig Before update on vtab1
For each row
Declare
Vno number95);
Begin
Select sno into vno from vtab1 where sno=30;
End;
Update vtab1 set sno=50;
Error: table apps.vtab1 is mutating, trigger/function may not see it.
To Avoid Mutating Errors We Use “Pragma Atonomous Transaction” (or) we can also use “statement level
trigger”.
RAJU CHINTHAPATLA