PL SQL
PL SQL
=========
Declare (optional)
Begin (mandotary)
Exception( optional)
End;(mandotary)
==================================
annonymous Block
=================
ex:
Declre
Begin
Exception
End;
named Block
===========
any name given to these blocks
it stored in database
ex:
Procedures, Functions, Packages , Triggers..
DBMS_OUTPUT.PUT_LINE:
=====================
DBMS_OUTPUT : package
PUT_LINE : procedure
Variables:
===========
ex: decalre
a number (10);
b varchar2(20)
c date;
syntax:
EX1
declare
a number(10);
begin
a := 5+3;
DBMS_OUTPUT.PUT_LINE(a);
END;
ex2:
Declare
B Varchar2(30);
begin
DBMS_OUTPUT.PUT_LINE(B);
END;
whenever we are using not null,constant values, we have intial the value at
declation section;
Declare
A number(10) :=10;
C number(10) :=20;
B Varchar2(30):= 'RAJEH';
D number(10);
begin
D :=A+C;
END;
Declare
D :=A+C;
END;
using select into clause we are retriving the values from table storing pl/sql
variables.
select into clause always return single record or single value at a time.
syntax:
example:
========
declare
V_EMPNO number(10);
V_ENAME VARCHAR2(30);
V_SAL number (10);
Begin
END;
/
example:
========
declare
V_EMPNO number(10);
V_ENAME VARCHAR2(30);
V_SAL number (10);
Begin
Varible attributes
==================
sysntax: tablename.columnname%type
declare
V_EMPNO emp.empno%type;
V_ENAME emp.ename%type;
V_SAL emp.sal%type;
Begin
END;
/
=====================
syntax: tablename%rowtype
EXAMPLE:
============
declare
V_EMP EMP%ROWTYPE;
Begin
select empno,ename,sal into V_emp.empno,v_emp.ename,v_emp.sal,v_emp.hiredate
from EMP where empno=7839;
END;
/
Bind variable
===============
These varibles are session variables.these values are used to pass the data
between client and database server.
: variable name
example:
variable g number;
decalre
a number(10) :=5000;
begin
:g := 5000/2;
end;
/
print g:
conditional stetements
========================
IF
1. simple IF condtion
2. IF ELSE condtion
3 elsif condtion
simple IF condtion
====================
synatx:
IF conition then
statements
end if
IF ELSE condtion
===============
IF Condition1 then
statements
ELSE
statements
END IF
elsif condtion
==================
IF Condition1 then
statements
ELSIF condition2 then
statements
ELSE
statements
END IF;
Example
===========
declare
V_DEPTNO Number(10);
Begin
IF V_DEPTNO=10 then
DBMS_OUTPUT.PUT_LINE ('ten');
END IF;
END;
exp2
====
declare
V_DEPTNO Number(10);
Begin
IF V_DEPTNO=10 then
DBMS_OUTPUT.PUT_LINE ('ten');
ELSE
DBMS_OUTPUT.PUT_LINE ('other');
END IF;
END;
/
EXP3:
====
declare
V_DEPTNO Number(10);
Begin
IF V_DEPTNO=10 then
DBMS_OUTPUT.PUT_LINE ('ten');
DBMS_OUTPUT.PUT_LINE ('Thirty');
ELSE
DBMS_OUTPUT.PUT_LINE ('others');
END IF;
END;
Control Statements
=================
1 simple loop
2 while loop
3 For loop
Body of the statements executed repeatedly . this loop also call infinite loop
simple loop
==========================
loop
statements;
end loop;
/
ex:
Begin
loop
dbms_output.put_line('welcome');
end loop;
end;
method 1: IF condition
ex:
declare
n number (10) :=1;
begin
loop
dbms_output.put_line (n);
IF n>=100 Then
Exit;
End if;
n:=n+1;
end loop;
end;
ex:
declare
begin
loop
dbms_output.put_line (n);
exit when n>=0;
n:=n+1;
end loop;
end;
While loop
========
syntax:
=======
while condition
loop
statements
end loop
ex1:
declare
n number (10) :=1;
begin
While a<=10
loop
dbms_output.put_line (n);
n:=n+1;
end loop;
end;
/
For loop
=======
Stntax:
Loop
statements;
End;
Example;
-------
declare
begin
For n in 1..10
loop
dbms_output.put_line (n);
end loop
end;
ex:
declare
begin
dbms_output.put_line (n);
end loop;
end;
Cursor
======
Curser is an private memory area is used to process multiple records and also these
records process is record by record.
static cursor
1 implicit curor
2 explicit cursor
implicit curor
===============
Implicit cursors are simple pl/sql prograns which contains select --- into clause
or DML statements.But these records are process
at a time.
wheneverwe are using in pl/sql block auto matically oracle server created an
memory area. these memory area also called context area or
Implici cursor.
Ex:
Declare
I EMP%ROWTYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE ( I.EMPNO ||' '|| I.ENAME ||' '|| I.SAL|| ' '|| I.DEPTNO);
END;
/
EX2:
Declare
I EMP%ROWTYPE;
J DEPT%ROWTYPE;
BEGIN
DBMS_OUTPUT.PUT_LINE ( I.EMPNO ||' '|| I.ENAME ||' '|| I.SAL|| ' '|| I.DEPTNO ||
' ' || J.DNAME||' '|| J.LOC);
END;
/
Explicit cursor
===============
set of rows return by a select statement is called 'Active set area" (internal
memory area).
Declare
Open
fetch
close
Dclare:
======
syntax:
Open
====
whenever we are opening the cursor set of rows return from table into cursor.
synatx:
Open Cursorname
Note: whenever we are open the cursor cursor pointer point the first record in the
cursor.
Close
=======
whenever we are closing the cursor all the resources allocated from the cursor
memory are released.
synatx:
ex:
==
Declare
V_ename varchar2(30);
V_sal number(10);
Begin
open c1;
Close c1;
End;
ex:
==
Declare
V_ename emp.ename%type;
V_sal emp.sal%type;
Begin
open c1;
fetch c1 into V_ename,v_sal;
Close c1;
End;
ex:
==
Declare
V_emp emp%rowtype;
Begin
open c1;
Close c1;
End;
1. %not found
2. %found
3. % is open
4. %row count
always these attributes are used along with cursor name only.
except %row count all other curor attributes return boolean value either true or
false
synatx:
ex:
Declare
v_name varchar2(30);
v_sal number(10);
Begin
open c1;
loop
fetch c1 into v_name, v_sal;
exit when c1% notfound;
DBMS_OUTPUT.PUT_LINE(v_name||' '|| v_sal);
end loop;
close c1
End;
/
declare
v_name varchar2(30);
v_sal number(10);
Begin
open c1;
loop
fetch c1 into v_name,v_sal;
end loop;
close c1;
End;
/
ex:write pl/sql cursor to transfer ename, salary of who are getting more then
2000?
Declare
i emp%type;
n number(10);
begin
n:=0;
open emp_cur;
loop
when emp_cur%notfound;
n:=emp_cur%rowcount;
end loop;
close emp_cur;
end;
/
syntax:
note: alway for loop index variable internally behave like a record type
variable(%rowtype)
whenever we are using cursor for loop no need to explicitly open, fetch and close
expmple;
-----------
declare
begin
for i in c1
loop
end loop;
end;
/
note: we can also elimate the declaration section of cursor using cursor for loops.
In this we can use select statement inplace of cursor name.
EX
begin
loop
end loop;
end;
/
parameterizied cursor
=======================
we are passing formal parameters in ursor declaration and we are passing actual
parameters in open curor.
syntax:
ex:
declare
i emp%rowtype;
begin
open C1(10);
Loop
fetch c1 into i;
exit when c1%notfound;
close c1;
end;
/
Declare
i emp%rowtype;
begin
OPEN C1('MANAGER');
loop
Fetch C1 into i;
dbms_output.put_line(i.ename);
end loop;
close c1;
OPEN C1('ANALYST');
loop
Fetch C1 into i;
dbms_output.put_line(i.ename);
end loop;
close c1;
end;
/
ex2:
Declare
i emp%rowtype;
V_job varchar2(30);
begin
begin
select job into V_job from emp where job='MANAGER' and rownum=1;
end;
loop
Fetch C1 into i;
dbms_output.put_line(i.ename);
end loop;
close c1;
begin
select job into V_job from emp where job='ANALYST' and rownum=1;
end;
loop
Fetch C1 into i;
dbms_output.put_line(i.ename);
end loop;
close c1;
begin
select job into V_job from emp where job='CLERK' and rownum=1;
end;
OPEN C1(v_job);
loop
Fetch C1 into i;
exit when c1%notfound;
dbms_output.put_line(i.ename);
end loop;
close c1;
end;
/
exp : write a pl/sql cursor program to display emplyee details and total salary
department wise?
declare
v_sal emp.sal%type;
begin
for i in c_dept
loop
v_sal :=0;
dbms_output.put_line('---------------------------');
dbms_output.put_line('---------------------------');
for j in c_emp
loop
if i.deptno=j.deptno then
v_sal:= v_sal+j.sal;
end if;
end loop;
dbms_output.put_line('total sal for department'|| ' '||i.dname || ' '||
V_sal );
end loop;
end;
/
ex : wrong
declare
cursor c_emp is select * from emp;
v_sal emp.sal%type;
begin
for i in c_emp
loop
v_sal :=0;
dbms_output.put_line('---------------------------');
dbms_output.put_line('---------------------------');
for j in c_dept
loop
if i.deptno=j.deptno then
v_sal:= v_sal+i.sal;
end if;
end loop;
end loop;
end;
/
%found
======
ex:
declare
i emp%rowtype;
n number(10):=0;
Begin
open c1;
loop
fetch c1 into i;
if c1%found then
n:=n+1;
end if;
end loop;
close c1;
if n>0 then
else
end if;
end;
/
genarally whenever we are using update, delete satemants oracle server establish
the locks automatically
If want establish locks before update ,delete then only we are using explicit
locking mechanisim through for update clause.
syntax:
where current of clause hold the most recently updated , deleted records from
cursor because internally where current Clause
works as Rowid only.
where we are where current of clause we must use for update clause.
synatx:
cursor cursor name is select * from tablename where condition for update no wait
update tablename set coulmnname= modified value where current of cursorname
ex:
i emp%rowtype;
Begin
open c1;
loop
fetch c1 into i;
exit when c1%notfound;
END IF;
END loop;
commit;
CLOSE C1;
End;
/
sql%notfound
sql%found
sql%isOpen
sql%rowcount
These attributes are used whenevr dml operations performed on the pure pl/sql
programs;
Exceptions
==========
1. predefined exceptions
2. user defined exceptions
3. unnamed exceptions
Predefined exceptions
======================
1. No_data_found
2 too_many_rows
3 Zero_DIVIDE
4. Invalid cursor
5 value_error
6 cursor _already_open
7 dul_val_on_idex
8 invalid_number
------
---
etc
when ever error occurs use appropriate exception names in exception hadler under
exception section/block
synatx:
-------------------
------------------
No_data_found
=============
wheanever we are using select into clause if requested data not available oracle
server voilets an error : ORA:01403 No data found;
Ex:
Declare
V_Name emp.ename%type;
BEGIN
Exception
END;
/
Note:
=======
when ever we are using DML statements with in the pl/sql block if requested data
not available also oracle server not return
any error. if want handle the one using inplicit cursor attibutes.
ex:
Begin
if sql%found then
dbms_output.put_line ('Your record deleted ');
end if;
if sql%notfound then
dbms_output.put_line ('Your record not exits ');
End if;
End;
/
too_many_rows
=============
when ever select into clause trying to return more tgan one row oracle server
violets an error ORA-01422: exact fetch return more Than
requested number of rows
ex:
Declare
i emp%rowtype;
Begin
EXCEPTION
WHEN TOO_MANY_ROWS THEN
Invalid_Cursor
===============
IF we are not performing proper operations on the cursor the oracle server return
error invalid Cursor
if we not opening the cursor also whn trying to close the cursor to handle the
exception using 'INVALID_CURSOR'
ex:
Declare
i emp%rowtype;
Begin
loop
fetch c1 into i;
EXCEPTION
end;
invalid_number,value_error
============================
when ever we are try to convert string to number oracle server voilets errors
invalid number , value error .
if our pl/sql blocks contains sql staements and try to convert string to number
oracle server voilets error .
to handle this error using 'INVALID_NUMBER' exception.
If our pl/sql blocks contains pure pl/sql staements and try to convert string to
number oracle server voilets error .
to handle this error using 'VALUE_ERROR' exception.
EXMPLE:
========
Declare
V_DEPTNO VARCHAR2(10) :='&DEPTNO';
V_NAME varchar2(10) :='&DNAME';
V_LOC VARCHAR2(10) := '&LOC';
Begin
EXCEPTION
WHEN INVALID_NUMBER THEN
END;
/
DECLARE
Z number(10);
begin
z := '&x'+'&y';
DBMS_OUTPUT.put_line(z);
EXCEPTION
WHEN VALUE_ERROR THEN
end;
/
We can also create our own exceptions and also raise wheanever necessary using
following setps.
steps:
declare
raise
exception handler
Declare
=========
In declaration section of PL/SQL block we are creating our own Exception using
exception type.
whenever necessary we are raising the Exception either begin or exception section
using raise stetement.
Exception handler
================
we can also handle the user defined Exception same as predifined Exception using
Exception handler.
synatx:
Exception
-------
EX
---- Write a PL/SQL program raise an Exception today;
Declare
Z Exception;
Begin
If to_char(sysdate,'DY')='MON' Then
raise z;
end If;
Exception
when z Then
end;
/
ex:
Declare
V_sal emp.sal%type;
z exception;
Begin
select sal into V_sal from emp where empno=7839;
raise z;
else
update emp set sal=sal+100 where empno=7839;
end if;
Exception
when z Then
end;
synatx:
-20000 to -20999
Raise_application_error(errornumber,message');
EX
ex:
Declare
V_sal emp.sal%type;
Begin
else
update emp set sal=sal+100 where empno=7839;
end if;
end;
/
SQLcode, SQLERRM
=================
These Predefined functions used to test the status of the Pl/sql block and also
catch the error number and error messages.
ex:
declare
v_sal emp.sal%type;
Begin
dbms_output.put_line(v_sal);
Exception
dbms_output.put_line(sqlcode);
end;
/
output: -1422
ex:
declare
v_sal emp.sal%type;
Begin
dbms_output.put_line(v_sal);
Exception
dbms_output.put_line(sqlcode);
end;
/
output: 100
ex:
declare
z Exception;
Begin
raise z;
Exception
when z Then
dbms_output.put_line(sqlcode);
end;
/
output: 1
we are declaring the Variables and assigned values into Variables and used this
variables in programing.
ex: write a Pl/sql program store sqlcode,sqlerrm return values into a saparate
table.
DECLARE
l_msg VARCHAR2(255);
l_sal emp.sal%type;
l_no number(10);
BEGIN
SELECT sal INTO l_sal FROM emp;
EXCEPTION
WHEN OTHERS THEN
l_no := SQLCODE;
l_msg := SQLERRM;
dbms_output.put_line(l_no ||' ' ||l_msg);
insert into h1 values(l_no,l_msg);
END;
/
Unnamed exceptions
===================
Other than oracle 20 predefined exceptions are handle using unnamed method only.
oracle 20 predefined exception names inplace of this one we are creating our own
exception using exception type and also
associate error number using Exception_init.
i.e oracle server identify the error at the time of compilation only.
ex:
declare
z exception;
Begin
delete from dept where deptno=10;
exception
when z then
dbms_output.put_line('not to delete master record');
END;
/
--- write pl/sql program using un named method handle -2291 error
declare
z exception;
Begin
insert into emp (empno,deptno) values(5,55);
exception
when z then
dbms_output.put_line('not insert other than primaray key values');
END;
/
Begin
insert into emp (empno,deptno) values(5,55);
exception
when others then
if sqlcode=-2291 then
end if;
END;
/
sub programs:
-------------
Sub programs are named pl/sql blocks. used to solve some particlar tasks.There are
2 types of sub programs supported by Oracle.
1. Procedures
2. Functions
1. Procedures
===============
Procedures are named Pl/sql blocks used to solve some particular tasks.Procedures
are may or may not return a value.
Genarally Procedures are used to improve the performence of the application because
first time only number of statements with in the Procedures
are comipled.
whenever creating the procedures we are create or replace beyond infront of the
procedures. Those procedures are stored In
1. procedure specification
2. procedure Body
syntax:
create or replace
IS/AS
Variabledeclaration, cursor declaration, user defined exceptions
Begin
---
--- procedure body
---
[exception]
end;
/
In
out
INOUT
excuting methods:
----------------
method1
method2
--------
Begin
end;
ex: develop a pl/sql stored procedure for passing EMPNO to display employee name
and salary;
is
V_ENAME emp.ename%type;
V_sal number(10);
Begin
select ename, sal into v_ename, v_sal from emp where empno=P_EMPNO;
End;
/
Excution method1
exec XXRR_EMPLOYEE(123);
/
Excution method2
begin
XXRR_EMPLOYEE(7839);
end;
-- develop a Pl/sql stored procedure to insert a record into DEPT table using
formal parameters:
is
Begin
Exception
End;
/
IN
=====
It is used to pass values into sub programs. IN mode basically like a constant in
procedure body.
ex: write a Pl/sql stored procedure using in parameters store a record in dept
table and also used default location?
is
Begin
Exception
End;
/
1. potion notation
2 . named notations
3. combination noatations
position notation
==================
exec XXRR_EMPLOYEE2(20,'SALES','BAN');
Named notations
===================
exec XXRR_EMPLOYEE2( P_DEPTNO =>30,P_DNAME =>'SALES',P_LOC =>'DHI');
Combination Notation
===================
exec XXRR_EMPLOYEE2( P_LOC =>'MUM'40,P_DNAME =>'MARKETING'); -- Not working
out
====
It is used to return values from the sub programs.
is
Begin
b:=a*a;
end;
note: whenever we are using OUT or INOUT modes in sub programs are excuting
following 2 methods.
VARIABLE z number;
exec p1(10,:Z);
print z;
output: 100
Declare
x number(10);
begin
p1(10,x);
dbms_output.put_line(x);
end;
output: 100
inout
=====
This mode internally behavious constant , intialized variable. Here also explicitly
we are sprcify INOUT Keyword.
is
Begin
a:=a*a;
end;
VARIABLE x number;
exec :x:=10;
exec p2(:x);
print x;
annonymous blockes
========================
declare
x number(10);
Begin
x:=10;
p2(x);
DBMS_OUTPUT.PUT_LINE(x);
end;
/
?
-- write a pl/sql stored procedure for passing empno return salary using INOUT
parameter?
IS
Begin
dbms_output.put_line(p_sal);
end;
/
method1
=======
VARIABLE x number;
exec :x:=7839;
exec p3(:X);
PRINT x;
method2
========
declare
z number(10);
begin
z:=7839;
p3(z);
DBMS_OUTPUT.PUT_LINE(z);
end;
NO Copy
===========
Ex
===
Begin
dbms_output.put_line(p_sal);
end;
/
IS
Begin
dbms_output.put_line(p_sal);
end;
/
exec p5('SMITH',:l_sal);
print l_sal;
declare
l_sal number(10);
begin
p5 ('SMITH',l_sal);
dbms_output.put_line(l_sal);
end ;
/
i emp%rowtype;
BEGIN
OPEN c1
loop
fetch c1 into i;
exit when c1%notfound;
DBMS_OUTPUT.PUT_LINE('*****************************************************');
end loop;
close c1;
Exception
END:
/
ex:
Begin
DBMS_OUTPUT.PUT_LINE(a/b);
EXCEPTION
DBMS_OUTPUT.PUT_LINE('cannot be zero');
END;
DBMS_OUTPUT.PUT_LINE('--------');
P7(5,0);
EXCEPTION
END;
/
exec p8;
authid current_user
=======================
this claue is used in sub programs . Genarally if we ant read the data from the
table and perform som dml operations
and provide security based on data we are using authid current_user clause in
before IS/AS
ex:
Authid current_user
IS
i emp%rowtype;
Begin
select ename, sal , empno into i.ename, i.sal,i.empno from emp where
empno=p_empno;
DBMS_OUTPUT.PUT_LINE(i.ename);
end;
/
Pragma Auonomus_tranaction
============================
In a sub programs , triggeres are autonamous in this trancation we are using Pragma
autonomus_transaction
this Pragma is used in decalaration section of the Pl/sql programs
wheanever we are using pragma Auonomus_tranaction we must use commit or roll back.
is
begin
commit;
End;
/
begin
insert into TEST_COUNTRY values ('ABC');
p9;
rollback;
end;
is
PRAGMA autonomous_transaction;
begin
commit;
End;
/
begin
insert into TEST_COUN values ('XYZ');
p10;
ROLLBACK;
end;
/
select * from TEST_COUN;
1. FUNCTIONS
===============
Functionsare named Pl/sql blocks used to solve some particular tasks and also
return sigle value;
whenever creating the Functions we are using create or replace beyond infront of
the function. Those functions are stored In
1. function specification
2. function Body
syntax:
variable,cursors ...
Begin
---
----
return expression;
end;
method1
======
method 2
=======
Declare
z varchar2(200);
Begin
Z:=F('RAJESWARA REDDY');
DBMS_OUTPUT.PUT_LINE(z);
end;
method 3
=========
variable z varchar2(200);
print z;
method 4
-------
Method5
======
begin
DBMS_OUTPUT.PUT_LINE(F('RAJESWARA REDDY'));
end;
ex
write a stored function for passing employee number return gross salary based on
following condtions.
gross: salary+hra+DA+PF
RETURN number
IS
V_SAL number(10);
V_HRA number(10);
V_DA number(10);
V_PF number(10);
GROSS number(10);
Begin
V_HRA :=V_SAL*0.1;
V_DA :=V_SAL*0.3;
V_PF :=V_SAL*0.4;
GROSS :=V_SAL+V_HRA+V_DA+V_PF;
RETURN GROSS;
END:
/
output: 9000
OUT Parameter
=============
Ex: write a stored function for passing deptno and return dname and Loc?
IS
Begin
return p_dname;
end;
excution:
----------
variable a varchar2(20);
variable b varchar2(20);
variable c varchar2(20);
exec :a := F2(30,:b,:c);
print b c;
Note: we can also user defined functions same like a perdufine aggrigate
functions and also these functions applied in
select satement.
---WM_Concat
ex: develop a pl/sql stored function to calculate tax for passing emp number and
also use folloeing conditions
V_sal number(10);
annalsal number(10);
IT number(10);
Begin
annalsal := V_sal*12;
IT:=annalsal*0.1;
ELSIF
annalsal >15000 and annalsal<20000 THEN
IT:=annalsal*0.2;
IT:=annalsal*0.3;
ELSE
IT:=0;
END IF;
RETURN IT;
end;
/
execute
========
Triggers
=========
Tiggers are also same as procedures and stored in database.It will automatically
invoked or fired wheanever
dml operations performed against tables or views.
staement level triggers are fired only once for a table where as row level
triggers fired for each row for a table.
synatx:
WHEN(conditions)
declare
-- trigger body
--
end;
Row level triggers are excuted for every row for a table.
i. e we are using for each row clause in triggers and also data internally stored
in rollback segment
qualifires(:new,:old)
except when clause alway we are using these qualifires along with : prefix
synatx:
:new.column name
or
:old.column name
Insert Update Delete
: new yes yes no
: old no yes yes
ex. wrete a trigger on emp table when ever user insrt a record salary should be
more than 5000.
Begin
if :new.sal<5000 THEN
end if;
end;
/
ex:
Begin
end;
/
insert into xx_emp (empno,job) values(3,'CLERK');
PRAGMA autonomous_transaction;
Begin
ROLLBACK;
end;
commit;
ex: write a Pl/sql trigger on emp table not to perform dml operations in saturday
and sunday?
Begin
end if;
end;
/
Triggering events
---------------
these events are used to writting conditions on multiple tables in a trigger body.
these clauses are used in either row level or statement level triggers.
1. inserting
2. updating
3. deleting
syntax:
IF inserting THEN
statements
staements
END IF
write a Pl/sql trigger on employee table not perform any dml operations?
Begin
if inserting then
end if;
end;
/
delete xx_emp1;
Begin
if inserting then
end if;
end;
/
insert into xx_emp1 (empno,ename) values(7,'CLERK');
delete xx_emp1;
Auto Increment
==============
In oracle we are genarating primary key and unique key values automatically we are
using auto incement concept.
ex:
create sequence S5
start with 1
Increment by 1;
/
create or replace trigger tr14
Begin
end;
/
ex:
Begin
:new.empno :=S5.nextval;
end;
/
is
V_tot number(10);
Begin
end;
/
call p20
29025
IF a row level trigger based on a table the trigger body cannot read the data from
same table
and we cannont perfor dml operations on same table.if we trying this oracle server
voilets on error
But staement level trigger does not view these type of error .
To overcome mutating problem oracle intraduced insted of triggers.
ex:
declare
a number(10);
Begin
dbms_output.put_line(a);
end;
/
there are 12 types of triggers supported by oracle
Row level
--------
before insert
before update
before delete
after insert
after update
after delete
staement lvel
--------------
before insert
before update
before delete
after insert
after update
after delete
system Triggers
================
we can also create triggers on schema level.these triggers also called DDL triggers
because here we are using ddl commands.
synatx:
---
end;
Begin
syntax
------
single trigger
===============
alter trigger trigger name enable/disable
all Triggers
===========
alter table table name enable/disable all trigggers
desc user_triggers
Packages
=========
Package does not have a parameters , cannot be invoked and can not be
nested.package having 2 parts
1. package specification
2. package body
Package specification we are defining public member data where as in package body
we are defining pravite member data.
Advantages of packages:
========================
1. we can group the objects which are related for siniler business functionality.
2. If we call the package the entire package will come into buffer. when we call
the next procedure for the packge it will pick from the
3 modularity(function,procedures overloading)
synatx:
package specification
-----------------------
IS/AS
global variables,
procedure decalaration
function decalaration
Cursor declararion
type declaration
end;
package body
-------------
IS/AS
procedure implementation
function implementation
end;
Execution
---------
ex:
procedure TEST_PROC;
procedure TEST_PROC1;
end;
is
procedure TEST_PROC
is
begin
dbms_output.put_line('procedure1');
end TEST_PROC ;
procedure TEST_PROC1
is
begin
dbms_output.put_line('procedure2');
end TEST_PROC1;
end;
/
Gobal variable
-------------
is
g number(10) :=300;
procedure test_p1;
end;
/
is
procedure test_p1
is
z number(10);
Begin
z := g*2;
dbms_output.put_line(z);
end;
is
Begin
return g*a;
end;
END;
/
exec XXRR_GLOBAL_PKG.test_p1;
ex 3:
IS
end XX_EMP_DETAILS;
/
IS
IS
i emp%rowtype;
begin
open c1;
loop
Fetch c1 into i;
End loop;
close c1;
End P1;
is
Tota_sal Number(10);
Begin
return Tota_sal;
end F1;
end XX_EMP_DETAILS;
/
exec XX_EMP_DETAILS.p1(10);
overloading subprograms
========================
overloading refers to same name is use to diffent purposes . Pl/sql also support
overloading subprograms
through packages.
ex:
is
end TEST_OVERLOADING;
/
create or replace package body TEST_OVERLOADING
is
IS
TOT Number(10);
Begin
TOT :=P_SAL+P_COMM;
dbms_output.put_line(TOT);
end ;
IS
TAX Number(10);
Begin
TAX :=P_SAL-P_TAX;
dbms_output.put_line(TAX);
END ;
end TEST_OVERLOADING;
note: If overloading programs having same number of parameters and same data types
those procedures executed through
Named notatiotion.
ex2:
is
procedure p1 (a number);
procedure p1 (b varchar2);
end TEST_OVERLOADING1;
/
is
procedure p1 (a number)
is
Begin
dbms_output.put_line(a);
end;
procedure p1 (b varchar2)
is
Begin
dbms_output.put_line(b);
end;
end TEST_OVERLOADING1;
/
exec TEST_OVERLOADING1.p1(5000);
exec TEST_OVERLOADING1.p1('RAJESH');
Forward declaration
====================
wheanever we are caling procedure with in other procedure ,wheanever we are using
forward declararion
ex
is
procedure p1;
End;
/
Create or replace package body test_forward
is
procedure p2;
procedure p1
is
Begin
p2;
end p1;
procedure p2
is
Begin
dbms_output.put_line('local procedure');
end p2;
End;
/
exec
exec test_forward.p1;
ex:
is
procedure DETATILS_emp;
end XX_FORWARD;
/
is
procedure INSERT_emp;
procedure delete_emp;
procedure DETATILS_emp
IS
i XXTEST_BACKUP%rowtype;
Begin
insert_emp;
open c1;
Loop
fetch c1 into i;
END LOOP;
Close c1;
end DETATILS_emp;
procedure insert_emp
is
Begin
delete_emp;
insert into XXTEST_BACKUP values(1,'RAJESH',5000);
insert into XXTEST_BACKUP values(2,'RAKESH',3000);
insert into XXTEST_BACKUP values(3,'LAKSHMI',2000);
insert into XXTEST_BACKUP values(4,'RAM',1000);
insert into XXTEST_BACKUP values(5,'ABC',3000);
commit;
End insert_emp;
procedure delete_emp
is
begin
delete XXTEST_BACKUP;
commit;
end delete_emp;
end XX_FORWARD;
/
exec XX_FORWARD.DETATILS_emp;
Advanced collections
======================
we can aslo create user defined data types in oracle though type keyword.
1. pl/sql record
2. index by table/pl/sql table
3. nested table
4. varry
5. ref curors
advanced collection:
1. pl/sql record
===============
This is an user define type used to store different data items into single
unit.This is also call as record type variable.
syntax:
ex:
IS
procedure p1;
end XX_RECORD_OKG;
/
IS
procedure p1
is
V_t t1;
Begin
end;
end XX_RECORD_OKG
/
set serveroutput on;
exec XX_RECORD_OKG.p1;
ex 2:
IS
procedure p1;
procedure p2;
end XX_RECORD_OKG1;
/
IS
procedure p1
is
V_t t1;
Begin
end;
procedure p2
is
V_t t1;
Begin
select empno,ename into V_t from emp where empno=7499;
end;
end XX_RECORD_OKG1;
/
exec XX_RECORD_OKG1.p2;
These are user defined data types used to store number of items in a single
unit.there are un constrant tables and there
tables are improve the performence of the application.
i.e these table are stored in SGA(system global area) .RAM memory area
syntax:
============
ex :
Declare
V_t t1;
Begin
v_t(1) := 10;
v_t(2) := 20;
v_t(3) := 30;
v_t(4) := 40;
v_t(5) := 50;
v_t(6) := 60;
dbms_output.put_line(v_t(3));
dbms_output.put_line(v_t.first);
dbms_output.put_line(v_t.last);
dbms_output.put_line(v_t.prior(3));
dbms_output.put_line(v_t.next(4));
dbms_output.put_line(v_t.count);
v_t.delete;
-- dbms_output.put_line(v_t(3));
dbms_output.put_line(v_t.first);
dbms_output.put_line(v_t.last);
dbms_output.put_line(v_t.prior(3));
dbms_output.put_line(v_t.next(4));
dbms_output.put_line(v_t.count);
end;
/
Collection methods
--------------------
COUNT - Returns the number of elements in a collection.
DELETE - Removes all elements from a collection.
DELETE (n) - Removes element n from an associative array. You cannot delete
individual elements from a VARRAY collection type. .
DELETE (n1, n2) - Removes all elements from n1 to n2 from an associative array.
You cannot delete individual elements from a VARRAY collection type.
EXISTS (n) - Returns TRUE if the specified element exists.
EXTEND - Appends a single NULL element to a collection.
EXTEND (n) - Appends n NULL elements to a collection.
EXTEND (n1, n2) - Appends n1 copies of the n2th element to a collection.
FIRST - Returns the smallest index number in a collection.
LAST - Returns the largest index number in a collection.
LIMIT -Returns the maximum number of elements for a VARRAY, or NULL for nested
tables.
NEXT (n) - Returns the index number of the element immediately following the
specified index.
PRIOR (n) - Returns the index number of the element immediately prior to the
specified index.
TRIM - Removes a single element from the end of a collection. You cannot trim
elements from an associative array collection type.
TRIM (n) - Removes n elements from the end of a collection. You cannot trim
elements from an associative array collection type.
EXMPLE:
Write a pl/sql program using EMP table retrive all employee names from emp
tables and store in index by tables and also
disply content of pl/sql table or index by table:
Declare
type t1 is table of Varchar2(10) index by binary_integer;
v_t t1;
i integer :=0;
Begin
open c1;
loop
i:=i+1;
dbms_output.put_line(i);
end Loop;
Close c1;
For i in v_t.first..V_t.last
loop
dbms_output.put_line(v_t(i));
end loop;
end;
/
Bull Collect
============
Bulk collect is one of the method of fetching the data from data base.
The sql engin to collect many rows at once and place them in collections. It will
improve the performence.
ex:
Declare
V_t t1;
begin
dbms_output.put_line(V_t(i));
end loop;
end;
/
If we want return bulk amout of data from database server into client application.
2. ref cursors
If we want develop result sets we are using functions and also we are
implementing server application and client application.
server application
==================
IS
end;
/
IS
Function F1 return t1
IS
V_t t1;
begin
end F1;
end XX_RETURN_RESULT_SETS;
/
Client application
====================
Declare
z XX_RETURN_RESULT_SETS.t1;
begin
z:=XX_RETURN_RESULT_SETS.F1;
For i in z.first..z.last
loop
end loop;
end;
/
syntax:
update tablename set column name= modified value where condition returning
col1,col2 ....bulk collect INTO
Collection variable.
ex: write PL/SQL program using bulk collect returning clause modify salary of the
employee 'CLERK' and stored these values
into pl/sql table and also diply the content of the pl/sal table?
IS
Type t1 is table of emp%rowtype Index by binary_integer;
v_t t1;
begin
for i in v_t.first..v_t.last
loop
end;
Ref cursors
===========
Ref cursors are user defined data type used to process multiple records.
Genarally static cursors bound only one select statement at compile time
where as in ref cursors only one active set area bound to number of select
staements dyanamically at runtime.
Genarally static cursor not allowed to pass as parameter to the sub program
(procedure,functions) but ref cursor is a variable we
are passing parameter into the sub programs.
strong ref cursor is a refcursor which contains return type where as weak
refcursor not having a return type.
syntax:
ex:
Declare
V_t t1;
I emp%rowtype;
begin
loop
fetch V_t into i;
end loop;
loop
fetch V_t into i;
end loop;
close V_t;
end;
/
ex:
Declare
V_t t1;
I emp%rowtype;
begin
end loop;
open V_t for select * from emp where deptno=10;
dbms_output.put_line('deptno 10 employee');
loop
fetch V_t into i;
end loop;
close V_t;
end loop;
close V_t;
end;
ex: write pl/sql program using refcursor wheanever enter 10th department display
the details from emp table and also whenever
user enter 20th department diaplay the details from dept table:
Declare
i emp%rowtype;
j dept%rowtype;
begin
If V_deptno=10 Then
open V_t for select * from emp where deptno=10;
loop
Fetch V_t into i;
close v_t;
end;
/
IS
end;
end;
end;
/
variable a refcursor;
variable b refcursor;
exec XX_REFCURSOR_TEST.p1(:a);
exec XX_REFCURSOR_TEST.p2(:b);
print a b ;
print a ;
print b ;
note:
synatax:
EX
Declare
v_t sys_refcursor;
I emp%rowtype;
begin
end loop;
end loop;
close V_t;
end;
/
These are user defined types to store multiple items in single unit.Genarally index
by tables not store in database
to overcome This problem oracle intraduced nested tables and vaarys.though the sql
we are storing nested tables ,varrys INTO
databse.
Before we are storing data into Varrays,nested tables we must intialize though
constractor.constractor name is same as type name.
Nested table is an un constrant table same like Index by table but not allowed to
negative index's and it will start with '1'
synatax:
example:(index by table)
declare
V_t t1;
begin
V_t(500) :=80;
dbms_output.put_line(v_t(500));
end;
/
output : 80
note: whenever we are using index by tables we are not required to reslove the
memory explicitly because based ON
specific key value and based on value field memory automatically allocated.
nested table
==============
declare
V_t t1 :=t1();
begin
V_t(500) :=80;
dbms_output.put_line(v_t(500));
end;
solution:
declare
type t1 is table of NUmber(10);
V_t t1 :=t1();
begin
v_t.extend(500);
V_t(500) :=80;
dbms_output.put_line(v_t(500));
end;
ex 2:
declare
V_t t1 :=t1();
begin
v_t.extend(5)
V_t(1) :=10;
V_t(2) :=20;
V_t(3) :=30;
dbms_output.put_line(v_t(1));
end;
note: without using "extend " collection method also we can store the data
directly into nested tables. in this we must
specify the atual data with in constractor itself.
declare
V_t t1 :=t1(10,20,30,40,50,60,70);
begin
dbms_output.put_line(v_t.first);
dbms_output.put_line(v_t.last);
for i in v_t.first..v_t.last
loop
dbms_output.put_line(v_t(i));
end loop;
end;
/
Declare
V_t1 t1;
v_t2 t1 :=t1()
begin
end if
end if
end;
clarification;
v_t1 t1 -- null
declare
V_t t1 :=t1();
begin
v_t.extend;
V_t(1) :=10;
dbms_output.put_line(v_t(1);
end;
/* |10|-|-|-| */
declare
V_t t1 :=t1(10,20,30,40,50);
begin
dbms_output.put_line(v_t.first);
dbms_output.put_line(v_t.last);
dbms_output.put_line(v_t.prior(3));
dbms_output.put_line(v_t.next(2));
dbms_output.put_line(v_t.count);
V_t.extend(3);
v_t(6) :=60;
v_t(7) :=70;
v_t(8) :=80;
for i in v_t.first..v_t.last
loop
dbms_output.put_line(v_t(i));
end loop;
v_t.delete;
dbms_output.put_line(v_t.count);
end;
/
trim: delete indexes last indexe onwards
delete(index): delete any element in any position with in nested table.
declare
V_t t1 :=t1(10,20,30,40,50);
begin
dbms_output.put_line(v_t.count);
v_.t trim;
dbms_output.put_line(v_t.count);
--v_t.delete(2);
for i in v_t.first..v_t.last
loop
dbms_output.put_line(v_t(i);
end loop;
v_t.delete
dbms_output.put_line(v_t.count);
end;
VARRAYS are user defined types used to store data items into single unit. these are
not un constrant tables.These types behavious like
Before we are storing data into Varrays,nested tables we must intialize though
constractor.constractor name is same as type name.
syntax:
type typename is varray(size) of datatype(size);
example:
Declare
V_t t1 :=t1('a','b','c','d' );
flag boolean;
begin
--- V_t.extend(10);
dbms_output.put_line (V_t.limit);
dbms_output.put_line (V_t.count);
dbms_output.put_line (V_t.first);
dbms_output.put_line (V_t.last);
dbms_output.put_line (V_t.prior(2));
dbms_output.put_line (V_t.next(3));
for i in v_t.first..v_t.last
loop
dbms_output.put_line (V_t(i));
End loop;
Flag :=v_t.exists(3);
--dbms_output.put_line ( Flag);
If flag=true then
dbms_output.put_line ('index 3 having element'||' '||v_t(3));
end if;
v_t.extend;
v_t(5):='e';
dbms_output.put_line (v_t(5));
Flag :=v_t.exists(5);
if flag=true then
else
end if;
v_t.extend(2,3);
for i in v_t.first..v_t.last
loop
dbms_output.put_line (V_t(i));
End loop;
v_t.delete;
dbms_output.put_line (V_t.count);
end;
/
note: vaary cannot delete particlar elements or range of indexes by using 'delete'
collection method
because vaarys is not sparse.vaarys does not have any gaps but we can delete all
elements by using delete collection method.
declare
begin
select ename bulk collect into v_t from emp where rownum<=10 ;
for i in v_t.first..v_t.last
loop
dbms_output.put_line(v_t(i));
end loop;
end;
bulk bind
==========
wheanever we are submittimg pl/sql into the server ,sql,pl/sql statements are
executed saparetly.i.e sql statements
whenever large amount of data is there oracle server degrade the performence
because of context swithing.To avoid
i. e we are executing all sql staements at a time using collections in this case we
are using either varrays or nested tables.
Genarally bulk binds used to improve the performence so insted of loops better to
use for all statements.
synatx:
for all variable name in lower bound .. upper bound dml statements.
Declare
v_t t1 := t1(10,20);
begin
forall i in v_t.first..v_t.last
end;
/
ex 2:
Declare
v_t t1 := t1(10,20,30,40,50,60);
begin
forall i in v_t.first..v_t.last
end;
/
/