Академический Документы
Профессиональный Документы
Культура Документы
1. Introduction to PL/SQL.
2. Decision Making.
3. Loops.
4. Sub –blocks
5. Cursors.
6. Exceptions
8. Stored Procs
9. Stored functions.
10. Packages
12. Arrays.
Declare
Declarative section.
Begin
End
/*Program*/
Begin
--------
--------
Begin
--------
--------
Begin
--------
--------
End;
----------
-----------
End;
---------
---------
End;
No limit for block within a block. This is known as Block level language.
• DDL commands not allowed. eg. Create , drop table are not allowed.
FIR number(8),
);
Anonymous Blocks
1.
Begin
End;
2. Declare
X number (4);
Begin
X := 100;
End;
assignment operator.
3. cl scr
Declare
Begin
End;
4.
Declare
X number(4);
Begin
X := &salary;
End;
Declare
X char(15) ;
Begin
X := ‘&ename’;
End;
Or
Enter the name of employee: 1056 /*This is not possible coz number to char
7. Declare
Begin
8. Declare
X number (8);
Begin
From emp
End;
Value of sal from emp table is transferred into tempp123 table and
5000 King
9. Declare
X number(8);
Y varchar2(35);
Hra number(6,2);
Begin
From emp
End;
stmnt to work:
Case 1
Declare
X number (4);
Case 2
10. Declare
X emp.sal%type;
Y emp.job%type;
Begin
from emp
End;
“ x emp.sal%type ” defines that datatype of x is same as that of the
11. Declare
x emp% rowtype;
Begin
Select * into x
From emp
End;
/
fname sal job
rowtype is used to store entire row
x.fname
x.sal x.job
Declare
a emp.sal%type,
b emp.job%type
);
x pqr;
Begin
End;
Declare
a emp.sal%type,
b emp.job%type
);
l number(4),
m abc
);
x emp_profile_pqr ;
Begin
From emp
End;
2. DECISION MAKING
IF STMNT:
1. Declare
X number (8);
Begin
from emp
If X>4000 then
else
end if;
End;
IF – ELSIF
2. Declare
X number (8);
Begin
From EMP
IF X>30000 then
else
END IF;
End;
3. Declare
comments */
Begin
If X then
End if;
End;
LOOPS
WHILE LOOP :
1. Declare
X number (4) := 1;
Begin
While X <10
Loop
Values (X , ‘Hello’);
X:=x+1;
EXIT;
End loop;
End;
DO WHILE LOOP:
5. Declare
X number(4) := 1;
Begin
Loop
End loop;
End;
FOR LOOP:
6. Declare
Begin
For X in 1..10
Loop
End loop;
End;
• Here X is only read only variable u can’t initialize and assign value to
it.
X number(4):= 100;
Begin
For X in 1..10
Loop
End loop;
End;
1 Hello
: “
9 “
8. Declare
Begin
For X in Y..Z
Loop
Insert into tempp123
End loop;
End;
output Enter X: 16
Y: 25
OR
Declare
Y number(4) ;
Z number(4);
Begin
For X in &Y...&Z
Loop
End loop;
End;
for X in 1..10
loop
loop
End loop;
End loop;
End;
/*multilane comment*/
GOTO stmnt:
1. Declare
X number (4):= 1;
Begin
Goto abc;
<<pqr>>
X := X+1;
<<abc>>
If X < 3 then
Goto pqr;
End if;
End ;
1 A
1 C
1 B
2 C
2 B
3 C
CODE.
Practical use: when u’ve large no. of nested loops use goto stmnt to come
out.
1. Declare
X number (4):= 1;
Begin
Declare
Y number (4):= 2;
Begin
X: = X+Y;
End;
End;
1 before sub
1 in sub
3 after sub
X number (4):= 1;
Begin
Declare
X number (4):= 2;
Begin
End;
End;
1 before sub
2 in sub
1 after sub
3. <<abc>>
Declare
X number (4) := 1;
Begin
Declare
X number (4) := 2;
Begin
Insert into tempp123
end;
end;
1. Implicit Cursor:
• Oracle created
or not)
1. Declare
X number(4);
Begin
If SQL%found then
X:= SQL%rowcount;
End if;
End;
Output 3 updated
2. Declare
X number(4);
Begin
Delete from EMP where deptno = 20;
If SQL%found then
X:= SQL%rowcount;
End if;
End;
Output 2 deleted
3. Declare
X number(4);
Begin
Insert into emp select * from semp; --semp structure similar to emp.
If SQL%found then
X := SQL%rowcount;
End if;
End;
Output 4 inserted
2. Explicit cursor:
• Used for handling multiple rows and process them row by row.
X emp%rowtype;
Begin
Open C1; ---will open the cursor and will populate it with the above
select statement
Loop
Fetch C1 into X;
unsuccessful
End loop;
End;
Cursor attributes:-
a) %notfound r
X emp%rowtype;
Y number;
Begin
Open C1;
Loop
Fetch C1 into X;
End loop;
Y := C1%rowcount;
Dbms_output.put_line(‘value of y is ‘||Y);
Close C1;
End;
-------
close C1;
endif;
Before opening cursor check if it is already open then close it & again it
can be opened. This concept is used for Resetting the cursor pointer.
Steps in cursor operation:
• Open cursor (fires the select statement in the cursor and populates
the data).
8. Declare
Begin
For X in C1
Loop
End loop;
End;
1. Here we do not declare the for variable, it will have same structure of
C1.
4. The for loop cursor automatically gets destroyed .No need of close
C1.
Declare
Begin
For X in C1
Loop
End loop;
End;
Output tempp123
10. Declare
Begin
For X in C1
Loop
End loop;
End;
11. Declare
Where deptno=dd;
Begin
For X in C1(10)
Loop
End loop;
For X in C1(30)
Loop
End loop;
End;
Declare
where deptno=dd;
Begin
For X in C1(&d1)
Loop
End loop;
For X in C1(&d2)
Loop
End loop;
End;
13. Declare
Begin
For X in C1(10,29000)
Loop
End loop;
End;
Declare
Begin
For X in C1(10)
Loop
End loop;
End;
15. Declare
from emp;
Begin
For X in C1
Loop
End loop;
End;
C1
A 5001
B 6001
C 7001
D 8001
E 9001
If alias not given then u cannot refer that field,but block will still
execute.
17. Declare
Begin
For X in C1
Loop
For Y in C2
Loop
End if;
End loop;
End loop;
End;
C2 emp
C1 dept
Note: For each deptno in C1 open C2 , go through C2, close C2, advance
Output:
1 trn
2 trn
3 trn
4 exp
5 exp
Faster programs:
18.
Declare
Where deptno=dd;
Begin
For X in C1
loop
faster.
Loop
End loop;
End loop;
End;
19. Fastest:
Declare
For X in C1
Loop
End loop;
End;
gives u same output but is much more faster than before two ways.
20. Declare
Begin
For X in C1
Loop
End if;
End loop;
End;
21. Declare
Begin
For X in C1
Loop
If X.sal > 7000 then
End if;
End loop;
End;
22. Declare
Begin
For X in C1
Loop
End if;
End loop;
End;
ARRAYS
• Temporary table
allows.
10 20 30
A
EXCEPTION
1. Predefined Exception.
Declare
Begin
end
Declare
Begin
====
END;
A. Predefined exception:
1 Declare
X number(8);
Begin
Insert into tempp123 values (1, ‘Too many rows Error’); -- error
handling routine
End;
o/p
FIR SEC
1 Hello
Note:-
Within the error handling routine, all PL SQL stmnts are allowed.
Control can’t be transferred from error handling routine to any other
2. Declare
X number (8);
Begin
Insert into tempp123 values (1, ‘no data found’); --error handling
routine
End;
3. Declare
X number(4);
Begin
X := 10000;----size exceeded
Insert into tempp123 values (1, ‘value error’); --error handling routine
End;
eg: x number(6,2)
x := 1000.786
4. Declare
X number (4);
Begin
Insert into tempp123 values (1, ‘value error’); --error handling routine
End;
5. Declare
X char(4);
Begin
X := 1000;
End;
6. Declare
X number(4);
Begin
col.*/
routine
End;
/
7. Declare
X number(4) :=10;
Y number(4) :=0;
a number;
Begin
X := X/Y;
a := sqlcode;
b := sqlerrm;
dbms_output.put_line(‘oracle says’||sqlerrm);
Insert into tempp123 values (a, ‘zero divide’); -- error handling routine
End;
9. Declare
X number(4) :=10 ;
Begin
Declare
X number(4) ;
Begin
X:=10000;
End;
End;
o/p
FIR SEC
10 before sub
1000 in sub
10 after sub
Declare
Begin
Declare
Begin
X :=10000;
End;
End;
parent block.
o/p
FIR SEC
10 before sub
1 main error
Declare
X number(4) :=1000000 ;
Begin
Declare
X number(4) ;
Begin
X:=1000;
End;
Insert into tempp123 values (X,’After sub’);
End;
Declare
X number(4) :=10 ;
Begin
Declare
X number(4):=100000;
Begin
---X:=100000;
End;
End;
1. too_many_rows
2. No_data_found
3. Value_error
4. Invalid_number
5. Zero_divide
6 invalid_cursor
7. cursor_already_open
8. DUP_value on index
Try to insert a duplicate value in a column that has a unique index on it.
9. logon_denied
10.Program_Error
11. Rowtype_mismatch
Fetch c1 into x
12. storage_error.
(memory problem)
• User created
• datatype
Eg:
11. Declare
X number(8);
abc exception;
Begin
raise abc;
end if;
end;
600 X<=5000
12. Declare
abc exception;
Begin
Declare
X number(8);
abc exception;
begin
Raise abc;
End if;
end;
end;
Declare
abc exception;
Begin
Declare
X number(8);
begin
Raise abc;
End if;
end;
End;
Declare
X number (8);
abc exception;
Begin
is’ ||sqlerrm);
End;
/
Declare
Begin
If sql%notfound then
End if;
End;
Note:--
STORED PROCEDURE
• It is a collection of statements.
• Only a single copy is brought into the RAM (program code shared by
all the users) when multiple users execute the same stored proc.
Begin
end;
3. SQL> execute P1
1 Hello
o/p 1 Hello
TO CALL IN PL SQL :
Declare
=======
Begin
=========
P1 ;
End;
declare
begin
p1;
end;
as
X number(4) := 10;
Begin
commit;
End;
Types of parameters(vvvvvvimp)
Call by VALUE
Cannot have defaults values
Must be a variable.
As
Begin
End;
As
Begin
End;
================
parameters.
Print g_name
Print g_sal
Print g_deptno
IN OUT Parameters:-
BEGIN
:g_phone_no := '8006330575';
END;
/
PRINT g_phone_no
EXECUTE format_phone (:g_phone_no);
PRINT g_phone_no
As
si number(6,2);
amt number(7,2);
begin
si := p * t * r / 100;
amt := p + si;
dbms_output.put_line(‘interest =’ || si);
dbms_output.put_line(‘amount =’ || amt);
end;
Exec sim_int(5000,3,9);
as
y number(4);
abc exception;
Begin
where empno = x;
if y = 0 then
raise abc;
end if;
-- commit;
end;
Begin
delete_emp (1001);
End;
Begin
dbms_output.put_line(‘before procedure’);
delete_emp(1);
dbms_output.put_line(‘after procedure’ );
End;
Rollback;
procedure.
stored ts
Describes procedure.
STORED FUNCTIONS
return number
as
Begin
Return y * y;
End;
Function created.
2. SQL> Declare
x number(4);
begin
x := fabc(10);
End;
return Boolean
As
Begin
Return true;
else
Return false;
end if;
End;
4. SQL> Declare
x number(4);
begin
x := &x;
if pqr(x) then
else
end if;
end;
can be used.
Ex:
return char
as
begin
return ltrim(rtrim(x));
end;
• Accept and return only valid SQL data types, not PL/SQL like boolean
declare
x number;
begin
x:=dml_call_sql;
end;
Declare
g_name varchar2 (50);
g_sal number;
g_deptno number;
x number;
begin
x:= query_empf(2, :g_name, :g_sal, :g_deptno);
end;
Print g_name;
Print g_sal;
Print g_deptno;
Managing Subprograms
Suppose the EMPLOYEES table is located within the scott schema, and
there is a user named Green.
Green can access the EMPLOYEES table only by way of the QUERY_EMP
procedure that Scott created, which queries employee records.
Definer‘s Rights
Imp Note:-
Using Invoker's-Rights
Invoker’s-Rights
To ensure that the procedure executes using the security of the executing
user, and not the owner,
use AUTHID CURRENT_USER. This ensures that the procedure executes
with the privileges and
schema context of its current user ie invoker .
Default behavior, as shown on the previous page, is when the procedure
executes under the security
domain of the owner; but if you wanted to explicitly state that the
procedure should execute using
the owner's privileges, then use AUTHID DEFINER.
Note:- AUTHID is introduced in Oracle8i. In previous versions of the Oracle
server, the behavior was based
on definer’s rights as described on the previous page.
SHOW ERRORS
PACKAGES
• The entire package will remain in the server RAM till you end
Package definition/specification:
as
End;
Package body:-
As
return number
is
X number (4);
Begin
where deptno=mdeptno;
Return x;
End;
is
X number(4);
begin
X := count_emp(mdeptno);
if X >0 then
end if ;
end;
End ;
To execute:
they are at hard disk then slow.But if in a package then they are
both
in RAM.
In PLSQL , we have :
1. Declare
=======
Begin
========
delemp.delete_emp(10);
========
end;
Declare
Y number (4);
Begin
Y: = delemp.count_emp(10);
values (Y,’employee’);
End;
is globally available.
Forward Declaration:-
End;
As
Is
Begin
Dbms_output.put_line(‘Pt1’);
Pr2;
End;
Procedure pr2
Is
Begin
Dbms_output.put_line(‘Pr2’);
End;
End;
Exec pg1.pt1(10);
As
Procedure one;
Procedure two;
End;
As
Procedure one
Is
Begin
Values (X,’A’);
X := X+1;
end;
Procedure two
is
X number (4) := 2;
Begin
Values (X,’B’);
X: = X+1;
End;
End;
OUTPUT:
1 A
2 B
1 A
as
Procedure one;
Procedure two;
end;
as
X number (4) := 0;
Procedure one
is
begin
X:= X+1;
Values (X,’A’);
end;
Procedure two
is
begin
X := X+1;
values (X,’B’);
Dbms_output.put_line(‘hello’);
end;
end;
OUTPUT :
1 A
2 B
3 A
• In the above program X is a global variable declared above the
static variable.
as
X number(4):=0;
Procedure one;
Procedure Two;
end;
To access X :
9. Declare
Y number (4);
Begin
Y := p_abc.X + 1;
values(Y,’Hello’);
p_abc.X:= p_abc.X + 1;
end;
database triggers.
As
end;
As
is
begin
Values (1,'proc_number');
End;
Is
Begin
Values (1,'proc_varchar');
End;
End;
Exec p_overld.one(‘a’);
Exec p_overld.one(1,2);
end;
as
is
begin
Values(1,'proc_number');
end;
is
begin
Values (1,'proc_varchar');
End;
End;
Exec p_overld.one(‘a’);
Exec p_overld.one(1);
as
Procedure one(x number ,y varchar2);
end;
As
is
begin
Values (1,'proc_number');
End;
Is
Begin
Values (1,'proc_varchar');
End;
End;
Exec p_overld.one(1,‘a’);
Exec p_overld.one(‘a’,2);
PG1
P1 N1 N2 DEFAULT
P2 N1
Note:-
One proc (p1) in a package pg1 has two number parameters and the
Solution :
exec pg12.p123(x=>1);
exec pg12.p123(n=>2);
Advantages of Packages:-
1. Improved Performance.
2. Overloading.
3.GLOBAL VARIABLES
declare
x number;
begin
x:=f1(x=>5); ---CAN be used when we are not sure abt the order of
arguments
end;
/
Database Triggers
Database Triggers :
database triggers.
Before delete
After delete
Before update
After update
b. Row level trigger Fires once for each and every row, in the DML
statement.
DML STATEMENT:
Update emp
---3ROWS UPDATED.
ST1:ONCE
RT1:THRICE
given table.
before insert
on emp
Begin
Values (1,’inserted’);
end;
other routines.
Before insert
on emp
Begin
Values (1,’inserted’);
Commit;
end;
SQL> Rollback;
Now temp data commited but the insert in emp is roll backed
Compare the difference between Statement level trigger and Row level
trigger:
Create or replace trigger t4 -----row level trigger
before update
begin
end;
before update
on emp
begin
End;
Update emp
Set sal=sal+100
Where deptno=10;
Begin
Values (1,'inserted');
end;
Before insert
On emp
Begin
end;
• This can be used to create two copies of emp ie. One can maintain
• One can’t pass parameter to a trigger. But “:new.sal” these are global
(deptno number,
saltot number);
Begin
end;
before delete
begin
values (1,’deleted’);
end;
before delete
on emp
begin
end;
Before delete
On emp for each row
Begin
End;
:old delete
:new insert
• Stores old values in the case of delete .Now tempp123 table called as
History Table.
• “ :old “ can be used with row level DB triggers . Read only global
bind variables.
Note:-
Insert :new
Delete :old
before delete
begin
before update
begin
end;
That is both (:old, :new) can be used for update. Thus , both history table
where deptno=20 ;
before update
begin
end;
/
3. SQL> update emp
set job=’Clerk’
Where empno= 1;
Now sal is not accessed in the emp table even then triggerT12 is invoked.
This will not affect the data but unnecessary processing will take place.
begin
end;
set sal=27000
Where empno= 1;
begin
Update deptot
set saltot = saltot - :old.sal
Update deptot
else
Update deptot
end if;
end;
UPDATE EMP
SET DEPTNO=30
update emp
where empno=1
we‘ve
Note:- the above trigger fires even when salary is not changed.
To avoid that:
begin
Update deptot
Update deptot
else
update deptot
end if;
end;
The old tablename is destroyed when it enters in the begin block and then
drop.
if inserting then
end if;
end;
before update
on emp
begin
null;
End;
Update emp
Set sal=sal+100
Where deptno=10;
output:
Mutating tables :
If in a Trigger, we try to access the same row which we are updating ,we get
Declare
v_minsal number;
v_maxsal number;
Begin
where deptno=:new.deptno;
End;
Update emp
Set sal=sal+100
Where deptno=20;
1 20
2 20
When you specify ON SCHEMA, the trigger fires for the specific user.
If you specify ON DATABASE, the trigger fires for all users.
DDL triggers fire only if the object being created is a cluster, function,
index, package, procedure, role, sequence, synonym, table, tablespace,
trigger, type, view, or user.
Implementing Triggers
You can use trigger for:
• Security
• Auditing
• Data integrity
• Referential integrity
• Computing derived data automatically
1. Security
Delete emp;
Update dept
set total_sal=(select sum(sal)
from emp
where emp.deptno =dept.deptno);
PL/SQL Tables(Arrays)
Create table emp_test
(empno number,ename varchar2(30));
Example 1:-
Declare
TYPE emp_plsqltab1 IS TABLE OF char(30) INDEX BY BINARY_INTEGER;
e emp_plsqltab1;
i binary_integer:=1;
ioCursor c1 is
Select empno, fname from emp;
Begin
for x in c1
loop
e(i):=x.fname;
insert into emp_test values(1,e(i));
i:=i+1;
end loop;
end;
Example 2:-
Declare
Type emp_rec is record (empno number, ename varchar2 (30) );
TYPE emp_plsqltab IS TABLE OF emp_rec INDEX BY BINARY_INTEGER;
e emp_plsqltab;
i binary_integer:=1;
Cursor c1 is
Select empno, fname from EMP;
Begin
For x in c1
Loop
e(i).empno:=x.empno;
e(i).ename:=x.fname;
Insert into emp_test values(e(i).empno,e(i).ename);
i:=i+1;
end loop;
end;
REF Cursor
A Cursor is a memory area; a Ref Cursor is a pointer to that.
A ref cursor is used to return a set of records from the procedure to the
front end. (Note a normal cursor cannot be used).
Dynamic SQL
Dynamic SQL:
Parse
Every SQL statement must be parsed. Parsing the statement includes
checking the statement's syntax and validating the statement, ensuring
that all references to objects are correct, and ensuring that the relevant
privileges to those objects exist.
Bind
After parsing, the Oracle server knows the meaning of the Oracle statement
but still may not have enough information to execute the statement. The
Oracle server may need values for any bind variable in the statement. The
process of obtaining these values is called binding variables.
Fetch
In the fetch stage, rows are selected(ie cursor is formed and returned)
and ordered (if requested by the query).
DBMS_SQL Package
DBMS_SQL.NATIVE );
DBMS_SQL.CLOSE_CURSOR(cursor_name);
END;
/
VARIABLE deleted NUMBER
EXECUTE delete_all_rows('emp', :deleted)