SlideShare ist ein Scribd-Unternehmen logo
1 von 54
PLSQL
PLSQL
Programming Language of Structure Query Language
Page 1 of 54
PLSQL
Features:
 Supports to execute a block of commands as a unit.
 Supports variables and constants.
 Supports conditional constructs.
 Supports iteration control statements.
 Supports error handling.
 Supports to define composite data types.
 Supports to execute the code automatically based on the event threw data base triggers.
 Supports to store and shared the code using subprograms.
PLSQL Block:
It is an collection of sql & program language statements.
There are 2 types.
1. Anonymous block
 Name less block
 Temporary block
Syntax:- Declare
<variable decl>
Begin
<exec stmts>;
End;
2. Named Block
 Block with fixed name.
 Stored permanently in database
Ex:- Subprograms.
Variable declaration:
 All sql data types are supported.
 Boolean is supported.
Declare
Veno number(4):=7900;
Vename varchar2(90);
Vjob varchar2(90) NOTNULL :=’CLERK’;
Doj date default sysdate;
Flag Boolean:= TRUE;
Pin constant number(6):=500038;
:= Assignment operator
= Comparission operator
Executable Statements:
 DML and TCL are not valid.
 DDL and DCL are not allowed.
Page 2 of 54
PLSQL
 Select ----- into statement.{ Used to retrieve data into Plsql variables.}
Select <column list> into <variables> from <table name>
Where <condition>;
 Used to print message & variables contents onto screen.
DBMS_OUTPUT.PUT_LINE(‘message Text’ || Variables);
 Comments
--Comment line
/*Multi Line
Comment*/
 Activates the DBMS stmt output buffer.
>set server output on;
Ex: Plsql Program retrieves the employ details and calculates the net salary and prints.
Declare
Veno number(4):=3400; or &employ;
Vname varchar2(90);
Vsal number(12,2);
Vcomm number(12,2);
Net number(12,2);
Begin
--Retrieve data from table.
Select ename, sal, comm. Into vname, vsal, vcomm from emp
Where empno=veno;
--Calculated net salary
Net:= vsal+nvl(comm., 0);
Dbms_output.put_line(‘employ details are:’||veno||’’||vename||’’||net);
End;
/
To save to local system(.sql file)
Save <filename>
To display the file
Get filename
To open the file in editor
Ed filename
To execute the file
Start filename or @filename
Page 3 of 54
PLSQL
Attribute Declaration:
Used to define the Plsql variables dynamically according to the table structure.
1. %Type:
Column type declaration.
Used to define the variables according to the specific column structure.
Syntax: variable <tablename>.<columnname>%type;
Ex: Declare
--using %type declaration
Veno emp.empno%type := &employ;
Vsal emp.sal%type;
Vcomm emp.comm%type;
Net emp.sal%type;
2. %Rowtype:
Record type declaration
Used to define the variables according to the complete table structure.
Syntax: variable <tablename>%rowtype;
Ex: declare
--using %Rowtype declaration.
I emp%rowtype;
Net number(19,9);
Begin
i.empno :=&empno;
select ename, sal, comm. Into i.ename, i.sal, i.comm from emp
where empno = i.empno;
net:= sal+nvl(comm., 0);
dbms_output.put_line(‘Employ details are:’||i.empno||’’||i.ename||’’||net);
end;
/
Page 4 of 54
PLSQL
Conditional Constructs:
Used to check for multiple conditions while manipulating data in plasql
1. If
2. case(8i)
1. Simple If
If <condition 1> then
<exec stmts>;
Elsif <cond 2> then
<exec stmts>;
--
--
Else < exec stmts>;
End if;
Ex: Plsql block checks for existing new comm. And assign new comm..
Declare
Veno emp.empno%type := &employ;
Vname emp.ename%type;
Vcomm emp.comm%type;
Begin
Select ename, comm. Into vname, vcomm from emp
Where empno = veno;
If vcomm is null then
Vcomm :=3000;
Elsif vcomm = 0 then
Vcomm :=2500;
Else vcomm := vcomm+vcomm*.25;
Endif;
Update emp set comm.= vcomm wehre empno = veno;
Dbms_output.put_line(veno||’’||vname|’’||vcom);
Commit;
End;
/
2. Case(8i) :
o Used to check for multiple conditions easily.
o It will check for equality condition.
o It can be used in “select” statement
Syntax:
1. Case <variable>
When <value1> then
<exec stmts>;
When <value2> then
<exec stmts>;
--
--
Page 5 of 54
PLSQL
--
Else <exec stmts>
End case;
2. Case
When <cond1> then <value1>
When <cond2> then <value2>
Else <value>
End case;
Using case construct:
Ex:
Declare
Grade char(1):=’&grade’;
Begin
Case grade
When ‘A’ then
Dbms_output.put_line(‘Grade is A’);
When ‘B’ then
Dbms_output.put_line(‘Grade is B’);
When ‘C’ then
Dbms_output.put_line(‘Grade is C’);
Else
Dbms_output.put_line(‘Grade is C’);
End case;
End;
/
Case in select:
select empno, ename, sal, job,
case
when job = ‘CLERK’ then ‘C’
when job = ‘salesman’ then ‘B’
when job in (‘Manager’, ‘Analyst’) then ‘B+’
when job = ‘President’ then ‘A’
else ‘D’
end “Grade”
from emp;
--It is used to generate reports.
Page 6 of 54
PLSQL
Iteration control statements: (LOOPS)
Supports to execute a block of stmts until conditions are true.
4 types:
1. simple loop
2. while loop
3. numeric for loop
4. cursor for loop
1. Simple Loop:
It is an infinite loop block.
Syntax: Loop
<exec stmts<;
End loop;
To break simple loop :
o Exit when(cond);
o If(cond) then
Exit;
End if;
Ex: --Prints first 10 numbers onto screen
Declare
A number(3):= 1;
Begin
Dbms_output.put_line(‘The numbers are:’);
Loop
Dbms_output.put_line(‘a’);
A := a+1;
Exit when (a > 10);
End loop;
Dbms_output.put_line(‘End of numbers’);
End;
/
2. While Loop:
It is an pre-tested loop.
Syntax: While (cond)
Loop
<exec stmts>;
End loop;
Ex: Declare
A number(3):=1;
Begin
Dbms_output.put_line(‘The numbers are:’);
While (a<=10) loop
Dbms_output.put_line(‘a’);
Page 7 of 54
PLSQL
A := a+1;
End loop;
Dbms_output.put_line(‘End of numbers’);
End;
/
3. Numeric For Loop:
It increments the variable by 1 always.
Variable can’t be assigned with a value in for loop.
Syntax: For <var> in [reverse] <value1>..<value2>
Loop
<Exec stmts>;
End loop;
<var> –Automatically defined by for loop.
Reverse(optional) –Accepts values in reverse order
.. –Range operator
Ex: Begin
Dbms_output.put_line(‘The numbers are:’);
For n in 1..10
Loop
Dbms_output.put_line(n);
End loop;
Dbms_output.put_line(‘end of numbers);
End;
Dbms_output.put : prints the results in same line.
Dms_output.put_line : prints the result in new line.
Put_line must be followed with “put” stmt to activate output
buffer.
4. Cursor For loop:
Used to perform cursor operations automatically
Improves performances
Syntax:
For <var> in <cur name>
Loop
<exec stmts>;
End loop;
Advantages:
No need to open cursor
No need to fetch rows
No need to check for end of rows
No need to close cursor
No need to declare variables
Ex: Declare
Cursor c2 is select * from dept;
Begin
For I in c2
Page 8 of 54
PLSQL
Loop
Dbms_output.put_line(c2%rowcount||’’||i.deptno||’’||i.dname||’’||i.loc);
End loop; --close cursor
End;
Declare
Cursor ecur
Is
For I in c2 loop
Declares I variable
Open cursor
Fetch 1 row into i
Check end of rows
Select empno, ename, sal, job, emp.deptno, dname, loc
From
Emp, dept
Where emp.deptno = dept.deptno;
Page 9 of 54
PLSQL
CURSORS:
 It is a temporary buffer used to hold the transaction data for manipulation purpose.
 It is not stored in database.
 It is not re-usable.
 It is valid in Plsql block only.
 It is created in logical memory only.
2 types
A. implicit cursors:
 Automatically defined by oracle whenever “DML” operations are performed by user.
 It has a fixed name “SQL”
 It gives the status of DML statements in Plsql block.
 It will not support cursor operations.
 It supports %found, %nofound, %rowcount, attributes.
Ex: TO update only 5 employees
Declare
Vdno number(2) := &dno;
Begin
Update emp set sal = sal+1000 where deptno = vdno;
If sql%notfound then
Dbms_output.put_line(‘Unable to update rows –No such dept exists’);
Elsif sql%rowcount > 5 then
Dbms_output.put_line(‘ Invalid operation –Can’t update more than 5 employees’);
Rollback;
Else
Dbms_output.put_line(sql%rowcount||’ employees are updated successfully’);
Commit;
End if;
End;
/
B. Explicit cursors:
Created by user in Plsql block used to retrieve multiple rows into Plsql block for
manipulation purpose.
1. Declaring cursor:
Syntax :
cursor <cur name> is <select stmt>;
2. Cursor Operations:
i. Open cursor:
Open <cur name>;
Used to open the cursor.
Memory will be allocated to cursor after opening it.
Page 10 of 54
PLSQL
ii.Fetch Cursor:
Fetch <cur name> into <var’s>;
Used to retrieve data from cursor to Plsql variables.
At a time it can retrieve only one row into variables
Generally fetch will be placed in loop
iii.Close Cursor:
close <cursor name>;
Used to close the cursor.
Memory allocated will be de-allocated.
3. Cursor Attributes:
Gives the status of cursor
<cur name>%<attribute>
i. %isopen (Returns true/false)
Returns True if cursor is opened successfully
ii. %found (Returns true/false)
Returns True if fetch stmt successfully retrieves the into Plsql var’s.
iii. %notfound (Returns true/false)
Returns true if fetch stmt fails to retrieve the row into Plsql var’s.
iv. %rowcount (Returns true/false)
Returns the no of rows successfully retrieved from cursor so far. Initially it holds
0.
After every successful fetch it is incr by 1.
Ex-1: Declaring cursor var with %Type
Declare
Cursor c1
Is
Select empno, ename, comm. From emp
Order by deptno;
Veno emp.empno%type;
Vname emp.ename%type;
Vcomm emp.sal%type;
Begin
Open c1;
If c%isopen then
Dbms_output.put_line(‘EMP NEW COMM’);
LOOP
Fetch c1 into veno, vname, vcomm;
Exit when c1%notfound;
If vcomm is null then
Vcomm := 3000;
Elsif vcomm = 0 then
Vcomm := 2500;
Else vcomm := vcomm+vcomm*.25;
Endif;
Update emp set comm.= vcomm where empno = veno;
Page 11 of 54
PLSQL
Dbms_output.put_line(veno||vname||vcomm);
End loop;
Dbms_output.put_line(c1%rowcount||’Employees are updated with new comm’);
Close c1;
Commit;
Else dbms_output.put_line(‘Unable to open cursor’);
End if;
End;
/
Declaring cursor var with rowtype.
Ex-2: Declare
Cursor c2
Is select * from dept;
I c2%rowtype;
Begin
Open c2;
Loop
Fetch c2 into I;
Exit when c2%notfound;
Dbms_output.put_line(c2%rowcount||’’||i.deptno||’’||i.dname||’’||i.loc);
End loop;
Close c2;
End;
Cursor with Scalar query:
Ex1: Declare
Cursor c2
is
select eno, ename, sal ,job,
(select min(sal) from emp where job = e.job) lopay,
(select max(sal) from emp where job = e.job) hipay,
from emp E order by job;
Begin
For k in c2
Loop
Dbms_output.put_line(k.eno||’’||k.job||’’||k.ename||’’||k.sal||’’||k.lopay||k.hipay);
End loop;
End;
/
Ex2: Calculate bonus for first 10 lowest employees.
Declare
Cursor c1
Is
Select eno, ename, sal, sal+nvl(comm., 0) net, job from emp
Order by sal;
I c1%rowtype;
Page 12 of 54
PLSQL
Bonus emp.sal%type;
Begin
For I in c1
Loop
If i.job = ‘CLERK’
Then bonus:= round(i.net*.25);
Elsif i.job = ‘EXECUTIVE’
Then bonus := round(i.net*.50);
Else then
Bonus := round(i.net*.1);
End if;
Dbms_output.put_line( i.eno||’’||i.ename||’’||i.job||’’||bonus);
Exit when(c1%rowcount >= 10);
End loop;
End;
/
Cursor with Parameters(8.0):
 Used to accept the input dynamically while opening the cursor.
 Supports to define generalized cursor.
 Maximum 32 parameters can be passed to cursor.
Ex-1: Calculates incr for employees depending on experience for particular dept only.
Declare
Cursor c1(dno number)
Is
Select * from emp
Where deptno = dno;
I c1%rowtype;
Incr number(12);
Expr number(2);
Begin
Open c1(&dno);
Loop
Fetch c1 into i;
Exit when c%notfound;
Net := i.sal + nvl(comm., 0);
Expr := round(months_between(sysdate, i.hiredate))/12);
If expr <=2
Then incr := net*.25;
Elsif expr<=5
Then incr := net*.5;
Else incr := net*.1;
End if;
Update emp set sal := sal+incr where eno = i.eno;
Page 13 of 54
PLSQL
Dbms_output.put_line(i.eno||’’||e.job||’’||expr||incr||i.deptno);
End loop;
Close c1;
End;
/
EX-2 :
Cursor c2(dno number, vjob varchar2)
Is select * from emp
Where deptno = dno and job = vjob;
Open c2(30, ‘clerk’);
For I in c2(20, ‘salesman’) loop
Ex-3:
Cursor c3(vcourse varchar2, vtime varchar2)
Is select * from student
where course = vcourse and timing = vtime;
open c3(‘oracle 9i’, ’10AM’);
for I in c3(‘oracle 9i’, ‘6PM’);
EX-4:
Cursor c4
Is select * from student
Where course = &course’;
It is valid in oracle sql environment.
Cursor parameters are used to pass values from other
application s/w tools.
Page 14 of 54
PLSQL
EXCEPTIONS:
 Errors in Plsql block are termed as exceptions.
 Error handling solutions are provided in exception block.
3 types…
1. Pre defined exceptions
Defined by oracle
Activated by oracle automatically.
Solution provided by user.
 No_data_found:
Automatically activated whenever select stmt fails to retrieve data into
variables.
 Too_many_rows:
Automatically activated whenever select stmt retrieves more than one row into
variables.
 Value_Error:
Automatically activated whenever data types are not matching.
 Zero_divide:
Automatically activated whenever invalid arithmetic operations is performed
(no/zero).
 Dup_val_on_index:
Automatically activated whenever duplicate values are inserted into unique
index column.
 Storage_error:
Automatically activated whenever there is lack of memory in server.
 Invalid_cursor:
Automatically activated whenever user fetch the rows from cursor without
opening the cursor.
 Time_out_on_resoursces:
Automatically activated whenever user performs an infinite loo process.
 Transaction_backed_out:
Automatically activated whenever there is an communication problem with
server.
 Login_denied:
Automatically activated whenever user name or pwd are not valid.
 Cursor_already_open:
Automatically activated whenever user opends the cursor which is already in
open state.
 Others:
General exception
Used to handle any pre-defined exception.
It will not support non-predefined/user defined exceptions.
Pseudo columns activated by other exception.
It must be last exception in exception block.
SQLCODE: Holds the currently raised error no.
SQLERRM: Holds the currently raised error message.
Page 15 of 54
PLSQL
2. User defined exceptions
 Defined by user.
 Activated by using “RAISE” stmt.
 Solution provided by user.
Ex: Plsql block handles diff types of errors.
Declare
Veno emp.eno%type := &employ;
Vname emp.ename%type;
Vsal emp.sal%type;
Salary_missing exception; --Declaring user defined excep
Begin
Select ename, sal into vname, vsal from emp
Where eno = veno;
If vsal is null then
Raise salary_missing; --Activating user defined excep
Else
vSal := vsal + vsal * .5
Update emp set sal = vsal where eno = veno;
Dbms(‘salary updated for’||veno||’is’||vsal);
Commit;
End if;
When no_data_found then
Dbms_output.put_line(‘No such emp found’||veno);
when too_many_rows then
dbms_output.put_line(‘More than one emp found for’||veno);
when salary_missing then
dbms_output.put_line(‘Emp has null salary –providing default pay’);
update emp set sal=5000 where eno= veno;
commit;
when others then
dbms_output.put_line(‘Error occurred’);
dbms_output.put_line(sqlcode||’’||sqlerrm);
end;
/
3. Non pre-defined exceptions (undefined exceptions)
 Defined by user.
 Activated automatically by constraints.
 Solution provided by user.
 Used to handle constraint violation of errors in Plsql.
Ex: Handling foreign key constraint error.
Declare
Vdno number(2) := &dno;
Employ_exists exception;
Page 16 of 54
PLSQL
Pragma exception_init(employ_exists, -2292);
Begin
Delete from dept where dno = vdno;
Commit;
Exception
When employ_exists then
Dbms_output.put_line(‘ Emp are still working –can’t remove dept’);
End;
/
EXCEPTION_INIT(Exception_name, Error_no);
Built-in sub-pgm used to provide exception name to the
constraint violation error
EXCEPTION PROPAGATION:
Declare
-------
-------
Begin
-------
-------
Begin
------- ERR
-------
-------
Exception
-------
-------
-------
Solution End; No Solution
-------
-------
Exception
------- Sol No sol
------- Quit with error
------- Quit with success
End;
/
Page 17 of 54
PLSQL
PRAGMA:
It is an special instruction to Plsql to execute sub program in declaration section.
DEPT EMP
-- --
-- --
Deptno(PK) eno
Deptno(FK)
Constraint violation error no’s:
-00001 Unique
-1400 Not null
-2290 Check
-2291 Parent not exists(ref)
-2292 Child records exists(ref)
EX-1: create table std_inf(roll number(4), name varchar2(90), course varchar2(20) check( course in
(‘oracle 9i’, ‘unix’, ‘D2k’)), fee number);
Insert into std_inf values( 101, ‘Sai’, ‘java’, 2300);
PLSQL block handling check constraint error
Declare
Invalid_course exception;
Pragma exception_init(invalid_course, -2290);
Begin
Insert into std_inf values(101, ‘Sai’, ‘java’, 2300);
Commit;
Exception
When invalid_course then
Dbms_output.put_line(‘ student course must be oracle 9i or unix or d2k’);
End;
/
EX-2: Using nested blocks, cursors with lock and exceptions.
Create table itemmast(itno number(2), name varchar2(90), qoh number(4), rol number(5));
Insert into itemmast values(&1, ‘&2’, &3, &4);
Create table ittran(itno number(4), tran_type char(1) [I-Issue(-), R-Receipts(+)], qty
number(5), updt char(1));
Insert inot ittran values(&1, ‘&2’, &3, ‘&4’);
Declare
Cursor tran is select into, tran_type, qty from ittran where upper(updt) = ‘N’
for update;
Cursor item is select * from itemmast;
Vname varchar2(20);
Vqoh number(4);
--cursor with lock
Page 18 of 54
PLSQL
Begin
For I in tran loop
Begin --nested loop
Select name, qoh into vname, vqoh from itemmast
Where itno = i.itno;
Exception
When no_data_found then
Dbms_output.put_line(‘no such item exists with itno’||itno);
End;
If i.tran_type = ‘R’ then
Vqoh := vqoh + i.qty;
Elsif i.tran_type = ‘I’ then
Vqoh := vqoh – i.qty;
End if;
Update itemmast set qoh = vqoh where itno = i.itno;
Update ittran set updt= ‘Y’ where CURRENT OF TRAN;
End loop;
Commit;
Dbms_output.put_line(‘Stock Report’); For k in
item loop
Dbms_output.put_line(k.itno||’’||k.name||’’||k.qty);
End loop;
Exception
When others than
Dbms_output.put_line(sqlcode||’’||sqlerrm);
End;
FOR UPDATE:
Locks the rows retrieved into cursor
WHERE CURRENT OF: Clause (8.0)
Used to locate the current row manipulated by
cursor
To use this cursor must be locked
Page 19 of 54
PLSQL
Composite data types: [User defined data types]
 Defined by the user.
 Valid in Plsql block only.
 They are not stored in the database permanently.
 They will not hold data.
 They are not re-usable.
 This will improve performance of oracle while retrieving or manipulating huge loads of data
into Plsql blocks.
2 types…
1. PLSQL Records:
It is an collection of elements of “different data types” stored at one location.
It is similar to “C Prog” structures.
Syntax:
Type <record name> is record
(element1 <datatype>,
Element2 <datatype>,
…..
Elementn <datatype>);
EX:
Declare --declaring Plsql record.
Type erec is record(eid number(4), name emp.ename%type, basic emp.sal%type, da
emp.sal%type, hra emp.sal%type, e.pf emp.sal%type, gross emp.sal%type);
E erec; --record type variable
Begin
e.eid:= &employ;
select ename, sal into e.name, e.basic from emp
where empno = e.eid;
e.da := e.basic*.24;
e.hra:= e.basic*.15;
e.pf:= e.basic*.15;
e.gross := e.basic+e.da+e.hra-e.pf;
dbms_output.put_line(e.eid||’’||e.name||’’||e.basic||’’||e.pf||’||e.gross);
end;
2. PLSQL Tables:
It is an collection of elements of same datatype stored in continous memory locations.
It is similar to “C Prog” arrays.
It is supported with an index automatically.
Syntax:
Type <table_name> is table of
<datatype> index by binary_integer;
Page 20 of 54
PLSQL
EX:
Declare --declaring Plsql tables.
TYPE names IS TABLE OF emp.ename%type
INDEX BY BINARY_INTEGER;
TYPE pays IS TABLE OF emp.sal%type
INDEX BY BINARY_INTEGER;
N names;
P pays;
Totsal number(12) := 0;
Ctr number(9):=1;
Begin --filling tables
For I in (select ename, sal from emp) loop
N(ctr):= i.ename;
P(ctr):=i.sal;
Ctr:= ctr+1;
End loop;
--printing table contents
For k in 1..n.count loop
Dbms_output.put_line(n(k)||’’||p(k));
Totsal:= totsal + p(k);
End loop;
Dbms_output.put_line(‘Total Salary is :’||totsal);
End;
N.COUNT : Gives no of elements in Plsql table
Page 21 of 54
PLSQL
Nested records and Plsql tables using records:
Declare
Type pf_rec is record(pfno number(9), amt number(12,2));
--Nested record
Type erec is record(eid number(9), name emp.ename%type, basic emp.sal%type, job
emp.job%types, pf pf_rec);
Type etab is table of erec
Index by binary_integer;
Ctr number(3):=1;
E etab;
Begin
--plsql table using nested records.
For I in (select empno, ename, sal, job from emp) pf.rec
Loop
E(ctr).eid := i.empno; erec
E(ctr).name := i.ename;
E(ctr).job := i.job; etab
E(ctr).pf.pfno := i.empno+1000;
E(ctr).pf.amt := round(i.sal * .15);
Ctr := ctr + 1;
End loop;
--printing table contents
Dbms_output.put_line(‘employee pay details are:’);
For k in 1..e.count
Loop
Dbms_output.put_line(e(k).eid||’’|| e(k).name||’’|| e(k).basic||’’|| e(k).job||’’||
e(k).pf.pfno||’’|| e(k).pf.amt);
End loop;
End;
/
Page 22 of 54
PLSQL
DATABASE TRIGGERS:
 A set of Plsql stmts stored permanently in database and automatically activated whenever
an event raising stmt (DML) is preformed.
 They are stored in user_triggers system table.
 They are use to impose business rules/user defined restrictions on table.
 They are also activated when tables are manipulated by either users or by other
application s/w tools.
 They provide high security on tables.
 TCL commands are not allowed in triggers.
Trigger parts:
1. Triggering even:
Indicates when to activate the trigger.
Before – insert/update/delete
After – insert/update/delete
2. Trigger types:
a. Row trigger:
Activates the trigger for every row manipulated by DML stmt.
b. Stmt trigger:
Activates the trigger for only once for 1 DML stmt (Default type).
3. Trigger restriction:
Used to stop the activation of trigger based on condition. If condition is true trigger is active.
4. Trigger Body:
A set of Plsql stmts.
Syntax:
Create or replace TRIGGER <trigger_name>
Before/after insert or update or delete (1)
[of <columns>] on <table_name>
[for each row (2)
When (<condition>) (3)
Declare
<var declaration>; ]
If condition is
true trigger is
activated
Begin
<exec stmts>;
[Exception
<exec stmts>;]
End;
Page 23 of 54
INSERT UPDATE DELETE
NEW valid valid invalid
OLD invalid valid valid
PLSQL
EX: Trigger converts student name to upper case automatically.
Create ore replace trigger up_con before insert on stu_info
For each row
Begin
:new.sname := upper(:new.sname);
End;
Triggering Events:
12 Events per table are allowed.
NEW & OLD (pseudo columns):
 Used to retrieve data from DML stmt
tempory buffer.
 Valid with “ROW” triggers only.
Before insert row before update row before delete row
Before insert stmt before update stmt before delete stmt
After insert row After update row After delete row
After insert stmt After update stmt After delete stmt
EX: Trigger checks fro valid increment.
Create or replace trigger valid_incr
Before update of sal on emp
For each row
Begin
If :new.sal <= :old.sal then
Column specification is supported with
update event only. Not valid with insert
and delete. operations(Row level
operations)
Raise_application_error(-20300, ‘Incr must be more than existing salary’;
End if;
End;
/
Raise_application_error(error no, error message);
Built in subprogram stops DML stmt execution and
displays the error message.
Error_NO range: -20002 to -20990
Oracle Reserved error no’s: -20000 to +20000
Page 24 of 54
PLSQL
Constraints vs Triggers:
 Constraint provide standard error message.
 Triggers provide user friendly error message.
 Constraints will for existing errors.
 Triggers will not check for existing errors.
 If constraint & trigger are defined on table, one time only trigger will be activated.
Ex: Trigger checks for valid salary according to the job.
Create table job_pays(job varchar2(20), losal number(10), hisal number(10));
Create or replace trigger chk_sal Before insert on emp for each
row When(new.job<>’PRESIDENT’) --If true trigger is
activated Declare
Minsal number(10);
Maxsal number(10);
Begin
Select losal, hisal into minsal, maxsal from job_pays
Where job =:new.job;
If :new.sal>maxsal and :new.sal<minsal then
Raise_application_error(-20201, ‘salary must be between’||maxsal||’and’||minsal||’for
job’||:new.job);
End if;
Exception
When no_data_found then
Raise_application_error(-20202, ‘No data found for dept’||:new.job);
End;
/
EX: Trigger adds the fee installment amt automatically into fee installments table
Create fee_installments(roll number(9), prev_fee number(9), curr_fee number(9), dop
date);
Create or replace trigger add_fee
Before update or insert on student
For each row
Begin
If inserting then
Keywords: Inserting, updating, deleting
Represents insert, update, delete operations.
Valid in triggers only
Insert into fee_installments values(:new.roll, :new.fee, :new.fee, sysdate);
Elsif updating then
Insert into fee_installments values(:old.rol, :old.fee, :new.fee - :old.fee, sysdate);
End if;
End;
/
Page 25 of 54
PLSQL
Statement level triggers:
 Trigger locks the table for DML operations to provide security.
 Trigger checks for
o Valid timings
o Weekends
o Public holidays
Ex:
Create or replace trigger security_chk
Before insert or update or delete on bankmaster
Declare
A number;
Begin
--check for valid timings.
If to_char(sysdate, ‘hh24’) not in (10,11,12,13,14,15,16,17,18) then
Raise_application_error(-20111, ‘No operations allowed –invalid timings’);
End if;
--check for week ends.
If to_char(sysdate, ‘dy’) in (‘sat’,’sun’) then
Raise_applicaiton_error(-20112, ‘No operations allowed –week ends’);
End if;
--check for public holidays
Select count(*) into a from holiday where to_date(hdate) = to_date(sysdate);
If a>0 then
Raise_application_error(-20113, ‘No operations allowed –public holidays’);
End if;
End;
/
Instead of triggers:
 Triggers supported only on “views”
 Used to perform DML operations on “join views”
Instead of ----insert, update, delete
EX:
Create view edept
As
Select empno, ename, job, sal, emp.dtno, dept.dtno dno, dname, loc from emp, dept
Where emp.dno = dept.dno;
Create trigger T1 instead of insert on edept
For each row
Begin
Insert into dept values(:new.dno, :new.dname, :new.loc);
Insert into emp(empno, ename, sal, job, dtno) values(:new.empno, :new.ename, :new.sal, :new.job,
:new.dtno);
End;
Page 26 of 54
PLSQL
Disabling triggers:
Alter table <table_name> disable all triggers;
Enabling triggers:
Alter table <table_name> enable all triggers;
Removing triggers:
Drop trigger <trigger_name>;
Checking for existing triggers:
 Desc user_triggers;
 Select trigger_name, trigger_event from user_triggers
Where table_name = ‘emp’;
 Select * from user_triggers
Where trigger_name = ‘chk_sal’
Create trigger T2
Before insert on temp for each row
Begin
Update temp set c2 = ‘HARI’;
End;
--It will not perform update in trigger body because 2 DML operations can’t
be performed on table at once
--It leads to a trigger mutation error while working in other s/w tools.
Page 27 of 54
PLSQL
SUBPROGRAMS:
 A set of Plsql stmts stored permanently database and used to perform a task.
 They can accept input from user as arguments dynamically.
 They are stored in “user_source” system table.
 They are reusable components.
 They can be shared with other users.
 They can be used n other application s/2 tools.
 They are faster in execution stored n compiled formed.
 They support modularity.
2 types…
1. Procedures
2. Functions
A huge task divided into
N no of sub tasks. Easy to
manage the logic easy to
debug errors.
1.Procedures:
 A sub prg type performs a task and will return a value.
 Generally procedures are used to perform DML operations on database.
 They can’t be called in SELECT stmt.
 Procedure can be used in sql, other application s/w tools, Plsql triggers
procedures, functions, packages, D6i.
Syntax:
Create or replace procedure <p_name> [(arguments MODE <datatype>)]
Is
[<var_declaration>]
Begin
EX:
End;
<exec stmts>;
Calling a procedure: procedure_name(arguments);
Create or replace procedure Sim_ins(p number, n number, r number)
Is
Si number(12);
Begin
Si := (p*n*r)/100;
Dbms_output.put_line(‘simple interest:’||si);
End;
/
SQL: PLSQL:
Desc sim_ins begin
Exec sim_ins(2,3,4); sim_ins(123,12,8.5);
End;
Page 28 of 54
PLSQL
2.Functions:
 A sub prog type performs a task and will return the value (Return only one value).
 Generally functions are used for reporting purpose or for calculating purpose.
 They can be called in SELECT stmt.
 Function can be used in sql, select, other application tools, Plsql, triggers, procedures,
functions, packages.
Syntax:
Create or replace function <function_name> [(arg’s MODE <datatype>)]
Return <datatype>
Is
[<var declaration>];
Begin
<exec stmts>;
Return (variable);
[Exception
<exec stmts>;]
End;
Calling a function: var := fun_name(arg’s);
EX:
Create or replace function si(p number, n number, r number)
Return number
Is
Si number(9);
Begin
Si := (p*n*r)/100;
Return(round(si));
End;
SQL: PLSQL:
i. Desc si Declare
Select si(1200,8,7) from dual; result number(12);
begin
ii. Variable result number result:=si(1200,9,7);
exec:result:=si(5400, 10, 9.5); dbms_output.put_line(result);
print result; end;
 Create table loan_master(cust_id number(4), cname varchare(9), amount number(12),
duration number(3), irate number(5,2));
 Insert into loan_master values(&1, ‘&2’, &3, &4, &5);
 Select cust_id, upper(cname), si(amount, duration, irate) interest from loan_master;
Page 29 of 54
PLSQL
EX-1: Function checks for leap year
Create or replace function chk_year(y number)
Return varchar2
Is
Begin
If mod(y,4) = 0 then
Return(‘leap year’);
Else
End if;
End;
Return (‘ Not leap year’);
Select chk_year(2008), chk_year(2010) from dual;
Variable result varchar2(90);
Exec:result:=chk_year(2012);
Print result;
SET AUTOPRINT ON Automatically prints the variable,
No need to use print stmt.
EX-2: Procedure cal the new comm. For all emp of particular dept.
Create or replace procedure call_comm(vdept number)
Is
Cursor c1
Is
Select empno, ename, comm. From emp
Where deptno = vdept;
I c1%rowtype;
Begin
For I in c1
Loop
If i.comm is null
Then
i.comm :=3000;
elseif i.comm = 0
then
else
end if;
i.comm:=2500;
i.comm = i.comm+i.comm*.25;
update emp set comm. = i.comm where empno = i.empno;
dbms_output.put_line(i.empno||’has been updated comm. For’||i.comm);
end loop;
commit;
end;
Page 30 of 54
PLSQL
 Desc user_source
 Select name from user_source;
To Remove sub prog’s:
 Drop procedure <proc_name>;
 Drop function <fun_name>;
 Create sequence s1 increment by 1 start with 11;
EX-3: Procedure adds a dept into Dept table
Create or replace procedure add_dept
(vname varchar2 default ‘unknown’, vloc varchar2 default ‘hyderabad’)
Is
Begin
Insert into dept values(s1.nextval, vname, loc);
Commit;
End;
 Desc add_dept
 Exec add_dept;
 Exec add_dept(‘sales’, ‘mumbai’);
 Exec add_dept(‘export’);
 Exec add_dept(vloc => ‘chennai’);
 Exec add_dept(vloc=> ‘pune’, vname => ‘software’);
Sharing Sub-Programs:
Scott:
 Grant execute on add_dept to user1;
User1:
 Desc scott.add_dept
 Exec scott.add_dept(‘Testing’);
Named notation:
Arguments are passed
based on their name.
 Insert into scott.dept values(22, ‘HR’, ‘sec’); --Error
User can manipulate the
table only through procedure
but not directly.
Parameter modes in sub-programs:
“MODE” indicates the behaviour of argument in sub program
3 types….
1. IN: (default mode)
 IN parameter is used to carry the input into subprogram.
 It can’t be assigned with a value in subprogram.
Page 31 of 54
PLSQL
2. OUT:
 OUT parameter is used to return the results from sub program.
 It can’t be assigned with a value in sub program
3. IN OUT:
 INOUT parameter is used to carry the input and return the results from subprogram.
 It can be assigned with a value in subprogram.
EX-1:
Create or replace procedure P1(a in out number)
Is
Begin
A:= A*A*A;
End;
SQL:
 Desc p1
 Var x2 number;
 Exec :x2 := 5; --intialising variable at sql
 Exec p3(:x2);
 Print x2
EX-2: Calculate factorial for given number and checks for odd/even number.
Create or replace function call_fact( n in number, f out number);
Return Boolean
Is
Fac number(9) :=1;
Begin
For I in 1..n
Loop
Fac := fac * I;
End loop;
-- cal factorial 5! = 5*4*3*2*1 =120
F:= fac; -- storing result in out parameter
If mod(n,2) = 0
Then
Else
End if;
End;
Return(TRUE);
Return(false);
Function returning
“Boolean” value (or) with
OUT parameter can’t be
used in sql or select stmt.
Using “CALL_FACT” function:
Declare
A number(9) := &num;
Fact number(90);
Begin
Page 32 of 54
PLSQL
If call_fact(a, fact)
Then
Else
End if;
Dbms_output.put_line(‘Given number is even’);
Dbms_output.put_line(‘Given number is odd’);
Dbms_output.put_line(‘Factorial of given number is:’||fact);
End;
Triggers vs Programs:
 Triggers are automatically activated by DML statements.
 Procedures & functions has to be explicitly activated by user.
Advantages:
 Code reusability.
 Faster execution of code.
 Easy to manage code.
 Executed in the oracle server memory even if it is activated from other application software
tools.
Page 33 of 54
PLSQL
PACKAGES:
 It is a collection of related var’s, cursors, procedures and functions.
 It is stored in “user_source” system table.
 It can be shared with other users.
 They will improve performance of oracle while accessing sub programs from client
environment.
 They support oops features live encapsulation, data hiding, and function over loading.
2 parts…
i. package specification:
It holds the declaration of variables, cursors, procedures and functions.
Syntax:
Create or replace package Package_name
As
<Var dec>;
Procedure <proc_name>(arg’s datatype);
Functions <fun_name>(arg’s datatype) return datatype;
End <pack_name>;
ii. Package body:
it holds the code of sub program.
Syntax:
Create or replace package body Package_name
As
Procedure <proc_name>(arg’s datatype)
Is
<exec stmts>;
End <proc_name>;
Functions <fun_name>(arg’s datatype) return datatype
Is
<exe stmts>;
End <fun_name>;
End <pack_name>;
Ex-1:
Create or replace package pack1
as
result number(12)
procedure add_num( a number, b number);
function mul_num(x number, y number);
end pack1;
create or replace package body pack1
as
procedure add_num(a number, b number)
is
begin
result := a+b;
Page 34 of 54
PLSQL
dbms_output.put_line(‘sum of numbers is:’||result);
end add_num;
function mul_num(x number, y number) return number
is
begin
result := x*y;
return (round(result));
end mul_num;
end pack1;
/
Using package elements:
 Exec pack1.add_num(2099, 8908);
 Select pack1.mul_num(200,22) from dual;
 Select ename, job, pack1.mul_num(sal,.15) pf,
pack1.mul_num(sal, 2) bonus from emp;
EX-2: LOCAL sub program are valid in package body only.
Create or replace package epack
As
Function gross(vsal number) return number;
Function experience(doj date) return number;
End epack;
Create or replace package epack
As
Function pf(vbasic number) return number is
Begin
Return( round(vbasic*.15));
End if;
Function gross(vsal number) return number is
Epf number(12);
Begin
Epf := pf(vsal);
Return (round(vsal+vsal * .25 + vsal*.35 – epf));
End gross;
Function experience (doj date) return number is
Begin
Return (round(months_between(sysdate, doj))/12);
End experience;
End epack;
/
Sub-program not
defined in
specification are local
sub programs. We
can’t call this pgm’s
from outside of
package.
Select empno, ename, job, round(epack.experience(hiredate) experience,
epack.gross(sal) “Gross pay” from emp;
Select ename, epack.pf(sal) “PF” from emp;
Page 35 of 54
PLSQL
--ERROR, you can’t call local subprogram.
Package with function overloading feature:
Create or replace package load_pack
As
Function add_data(a number, b number) return number;
Function add_data(a varchar2, b varchar2) return varchar2;
End load pack;
/
Create or replace package load_pack body
As
Function add_data(a number, b number) return number
Is
Begin
Return (a+b);
End add_data;
Function add_data(a varchar2, b varchar2) return number
Is Begin
Return(a||’ ‘||b);
End add_data;
End load_pack;
/
Removing Pack:
 Desc load_pack;
 Select load_pack.add_data(5,6) total,
load_pack.add_data(‘Satya’, ‘M’) name from dual;
 Drop package <pack_name>;
Sharing Pack:
 Grant execute on load_pack to user1;
To view existing package body:
 Select text from user_source wehre name = ‘pack1’;
Page 36 of 54
PLSQL
8.0 Features:
Returning into clause:
o Used to return the values through “DML” stms.
o Used with update and delete stmts.
Ex:
 Var a varchar2(20)
 Var b number
 Update emp set sal = sal+3000 where empno = 7900
Returning ename, sal, into :a, :b;
 Print a b
 Delete from emp where mepno= 7920
Returning ename, sal into :a, :b;
 Print a b
Bulk Collect:
o Used to return bulk data into Plsql variables
o Variables must be of Plsql table type only
o Improves performance while retrieving data.
o Used with select, update, delete, fetch stmts.
Examples:
Using in select stmt:
 Declare
Type names table of emp.ename%type
Index by binary_integer;
Type pays table of emp.sal%type
Index by bindary_integer;
N names;
P pays;
Begin
--Retrieving all emp’s in 1 transaction
Select ename, sal bulk collect into N, P from emp;
--Printing table contents
Dbms_output.put_line(‘Employ details are’);
For I in 1..n loop
Dbms_output.put_line(n(i)||’’||p(i));
End loop;
End;
Using in update stmt:
 Update emp set sal=sal+3000 where deptno = 30
Returning ename, sal bulk colleck into n,p;
Using in delete stmt:
 Delete form emp where job = ‘CLERK’
Returning ename, sal bulk collect into n,p;
Page 37 of 54
PLSQL
Using in fetch stmt:
 Declare
Type names is table of emp.ename%type
Index by binary_integer;
Type names is table of emp.sal%type
Index by binary_integer;
N names;
P pays;
Cursor c1
is
Select ename, sal into n, p from emp;
Begin
Open c1;
Fetch c1 bulk collect into n,p;
--printing table contents
For I in 1..n count Loop
Dbms_output.put_line(n(i)||’’||p(i));
End loop;
End;
/
Dynamic SQL:
o Supports to execute DDL commands in Plsql block.
Execute immediate(‘DDL stmt’);
EX:
 Begin
Execute immediate(‘create table employ(ecode number, ename varchar2(90), sal number));
End;
 Begin
Execute immediate(‘drop table employ1’);
End;
NOTE:
Table can’t be manipulated
in same Plsql block.
Using Long and Raw data types:
Long:
o Used to represent numbers or character values
o Maximum limit is 2GB.
o But only once it can be used in table.
Raw(n):
o Used to represent images
o Max limit is 256 bytes(7.0)/2000 bytes (8.0)
Long Raw:
o Used to represent images upto 2 GB.
o Raw and long raw can be manipulated by GUI tools only
Page 38 of 54
PLSQL
Ex:
 Create table emp(ecode number(3), ename varchar2(20), sal number(12,2), description long,
deptno number(2));
 Create table ephoto(ecode number(4), photo long raw);
 Create table customer(cust_id number(4), cname varchar2(20), addr varchar2(50), photo
longraw);
File input & output (8.0):
 Used to transfer oracle table contents to OS file and OS file content to oracle table.
 Standard package holds all functions (arthematic, date, general);
UTL_FILE  Built in package supports file operations.
Sub-Programs in UTL_FILE pkg:
 Fopen:
Used to open the file in the specified mode and returns the address of the file.
Mode R  Read, W  Write, A  Append
 Fclose: Used to close the file
 Get_line: Used to read a line from file to Plsql variable.
 Put: Used to write a line into file but in New line.
 Put_line: Used to write a line into file but in new line.
 Fflush: Writes the file content from temporary buffer to physical memory (saving file
into OS)
 File_type: Data type
Used to define the variable to hold the address of file.
 Invalid_file_handle, Read_error:
Pre-defined exception automatically activated while working with files.
Plsql block transfers data from oracle table to OS file.
Ex: Plsql procedure transfer data from OS file to database table.
Create or replace procedure load_student(pdir varchar2, pfile varchar2)
Is
Vfile utl_file.file_type;
Vtext varchar2(200);
Vname varchar2(20);
Vcourse varchar2(20);
Vfee number(5);
Fcomma number(3);
Scomma number(4);
Begin
Vfile:= utl_file.fopen(pdir, pfile, ‘R’);
Page 39 of 54
PLSQL
Loop
Begin
Utl_file.get_line(vfile, vtext);
Exception
When no_data_found then
Exit;
End;
Fcomma := instr(vtext, ‘,’,1,1);
Scomma := instr(vtext, ‘,’, 1,2);
Vname := substr(vtext,1,fcomma,-1);
Vcourse:=substr(vtext, fcomma+1, soma-fcomma);
Vfee := substr(vtext, scomma+1);
Insert into student values(s1.nextval, vname, vcourse, vfee);
End loop;
Commit;
Exception
When utl_fjile.read_error then
Dbms_output.put_line(‘unable to read the file….’);
End;
 Exec load_student(‘c:’, ‘student.txt’):
Note: Provide the below parameter in “init.ora” file
(open in notepad)
UTL_FILE_DIR = ‘C:Oracleora92Bin’
Init.ora --system parameter file.
Holds the parameter defined for oracle server.
Page 40 of 54
PLSQL
Object Technology(8.0):
 Object is a collection of different datatypes stored at one location.
 It will not hold data
 It can have methods (functions) defined in it.
 They are stored permanently in “user_types” system table
 They support inheritance feature.
 They can be shared with other users.
 They are reusable components.
CDT: (composite data type)
 Object  ‘C’ structure
 Object with methods  ‘C++’ class
 Nested tables
 Varying arrays
EX: Plsql records
Plsql tables
Syntax:
Create type <obj name> as object
(element1 <datatype>,
ele 2 <datatype>,
------
Element N <datatype>);
Object types:
2 types…
1. Column object:
Only few columns of table represent objects.
2. Row Object:
Entire table structure depends on object.
 Create type etype as object( eid number(9), ename varchar2(90), sal number, deptno
number(9));
 Create table etab of etype;  Row object
 Desc etab = desc etype
 Insert into etab values(1001, ‘RAM’, 210,10);
 Select * rom etab;
 Select eid, ename, sal from etab;
 Create table employ(einfo etype, job varchar2(90), hiredate date);  Column object
Ex:
 Create type addr_type as object (hno varchar2(90), street varchar2(90), city varchar2(90), pin
number(6));
 Create type Pf_type as object (pfno number(5), amt number(4));
 Desc addr_type;
 Desc pf_type;
 Select * form user_types;
Page 41 of 54
PLSQL
Naming object:
 Create table student(roll number(3), sname varchar2(20), address addr_type, course
varchar2(90), fee number(5));
 Desc student;
 Insert into student values(101, ‘SAI’, addr_type(’12-A’, ‘ameerpet’, ‘Hyd’, 500038), ‘oracle
9i’, 2500);
 Select * from student;
 Select sname, address from student;
 Select sname, s.address.city, s.address.pin from student s;
 Update student s set s.address.hno = ‘308A’ where roll=101;
 Delete from student s where s.address.city = ‘hyd’;
Objects will not support constraints.
Trigger check for null values in city.
Create trigger city_chk before insert on emp
for each row
begin
if :new.address.hno is null then
Raise_aplication_error(-20100, ‘Student hno can’t be null’);
End if;
End;
Sharing object:
Scott: Grant execute on addr_type to user1;
User1:
 Create table supplier(sid number, sname varchar2(90), saddr scott.addr_type);
 Select sname s.saddr.city from supplier s
Nested objects: [Max 32 levels]
 Create type person_type as object(pname vachar2(20), paddr addr_type);
 Desc person_type;
 Create table customer(cid number, cinfo person_type);
 Select cid, c.cinfo.paddr.city, c.cinfo.paddr.pin from customer c;
 Desc customer;
 Drop type <obj_name>;
 Drop type addr_type;
 Drop type pf_type;
Purity level test:
 Checks for member functions are having DML stmts or not.
 DML are not valid in member functions.
Page 42 of 54
PLSQL
Restrict_references: Built-in sub program used to check
for DML stmts in methods
WNDS: Write no database state
Pragma: Instruction to Plsql supports to execute sub
program in declaration section
Object with methods:
 Create or replace type etype as object(ecode number, name varchar2(90), basic number(90),
job varchar2(4), hiredate date,
member function gross(vbasic number) return number,
pragma restrict_references(gross, WNDS),
member function experience(doj date) return number,
Pragma restrict_references(experience, WNDS));
 Create or replace type body etype as
Member function gross(vbasic number) return number
Is
Begin
End;
Return(round(vbasic+vbasic*.25+vbasic*.35-vbasic*.15));
Member function experience(doj date) return number
Is
Begin
End;
End;
Return(round(months_between(sysdate, doj))/12);
 Create table etab of etype;  Row object
 Insert into etab values(1001, ‘RAM’ 3000, ‘Analyst’, ’10-dec-01’);
 Select ecode, name, job, basic, e.gross(basic) “gross”, e.experience(hiredate) “exp in years”
from etab e;
Page 43 of 54
PLSQL
Collections(8.0):
 A group of similar rows stored at one location.
2 types…
1. Nested table:
 Table with in a table
 A column holds a table of contents in it.
Ex:
 Create type book_type as object (bookid number(4), title varchar2(90), doi date, dor
datae);
Object representing table of books
 Create type books is table of book_type;
 Create table stu_lib(roll number, name varchar2(90), course varchar2(90), binfo books)
nested table binfo store as book_table;
 Desc book_type;
 Desc books;
 Desc stu_lib;
 Insert into stu_lib values(101, ‘RAM’, ‘Oracle 9i’,
books(book_type(11, ‘sql’, sysdate, sysdate+10),
book_type(12, ‘plsql’, sysdate, sysdate+11),
book_type(13, ‘dba’, sysdate, sysdate+15)));
 Select * from stu_lib;
 Select name, binfo from stu_lib;
Roll Name Course Binfo
101
102
Book id Title Doi Dor
11
12
13
2. Varrying arrays examples:
 It is an array of elements stored in a column.
EX:
i. Create type blist is varray(5) of varchar2(25);
--Object representing array of books.
ii. Create table items(itno number, name varchar2(90), brands blist);
iii. Insert into items values(102, ‘Micro-oven’,
blist(‘LG’, ‘ONIDA’, ‘IFB’));
iv. desc blist
desc items
Page 44 of 54
PLSQL
v. update items set brands = blist(‘LG’, ‘ONIDA’, ‘IFB’, ‘KENSTAR’,
‘SAMSUNG’) where itno = 102;
vi. select name, brands from items;
BINFO
Roll Name Course Bid Title Doi dor
101 11
12
13
102
Nested table Varray
Stored outside the table Stored with in the table
DML is allowed DML is not allowed
Stores unlimited data stores limited data.
Note:
 Collections will not support constraints
 Long, raw, lob data types are not valid in
collections.
 Collections will not support dev-6i, VB (GUI
tools)
 Java supports collections.
DML on nested tables:
THE: Operator is used to perform DML on nested table.
EX:
Inserting a book(only 1 book allowed)
 Insert into
THE(select binfo from stud_lib where roll=101)
Values(book_type(15, ‘DBA’, sysdate, sysdate+10));
Changing a book details
 Update
 Update
THE(select binfo from stu_lib where roll = 101)
Set dor=sysdate+3 where book_id = 12;
THE(select binfo from stu_lib where roll=101)
Set title=’Tuning’ where book_id = 15;
Removing a book info
 Delete from
THE(select binfo from stu_lib where roll=101)
Where book_id =12;
Page 45 of 54
PLSQL
LOBS – Large Objects(8.0):
 Used to represent huge loads of fdata
 Max limit is 4 GB
 N columns allowed per table
4 types…
1. CLOB – Char Large Object
Used to represent char information upto 4 GB.
2. NCLOB – Native char large object
Used to represent other language text.
*Nchar, Nvarchar2 -- Represents other language test.
3. BLOB – Binary large object
Used to represent images upto 4GB.
4. BFILE – Binary File
Used to hold the address of OS file.
Representing Null values:
CLOB - Empty_CLOB( )
NCLOB- Empty_NCLOB( )
BLOB - Empty_BLOB( )
BFILE - Skip the column while inserting
EX: Create table emp_lob(ecode number, name varchar(90), description CLOB, sal number,
photo BLOB, edocs BFILE);
Making logical dir to insert Bfile value:
DBA > Grant create any directory to scott;
SCOTT > Create directory emp_dir as ‘C:employbonds’;
> Insert into emp_lob values (101, ;’RAM’, ‘………’, 2100, empty_BLOB( ),
Bfilename(emp_dir, ‘e101.doc’));
Built in subprogram
used to represent OS
file details into bfile
> Select ecode, ename, sal, description from emp_lob;
Page 46 of 54
PLSQL
Temparary Tables(8i):
 Used to hold the information in logical memory but not in physical memory.
 They hold the data for a particular period of time but not permanently.
EX-1:
 Create global temporary table temp(c1 date) on commit delete rows;
 Insert into temp values(sysdate);
 Select * from temp; --28-Mar-2012
 Commit;
 Select * from temp; -- No rows.
EX-2:
 Create global temporary table(c1 date) on commit preserve rows;
 Insert into temp values(sysdate);
 Select * from temp; --28-Mar-2012
 Commit;
 Select * from temp; --28-Mar-2012
 Exit;
 Select * from temp; --No rows.
Autonomous Transactions:
 Defines the trigger as an independent transaction
 Allows TCL commands in triggers.
Syntax:
Create trigger add-incr before insert on incr
For each row
Declare
Pragma autonomous transaction;
Update emp set sal = sal+ :new.amt
Where empno = :new.empno;
Commit;
End;



Select empno, sal from emp;
Insert into incr values(7900, 4000);
Select empno, sal from emp;
--7900 8000
--7900 12000



Select empno, amt from incr;
Rollback;
Select empno, amt from incr;
--7900 4000
--No rows
 Select empno, sal from emp; --7900 12000
Page 47 of 54
PLSQL
REF CURSORS:
Dynamic Cursors:
 Supports to define the cursor without select stmt.
 Select stmt will be provided while opening cursor.
 Used to send cursor as an parameter in sub programs.
 Made easy to transfer huge data through sub programs.
Syntax:
Type <ref cursor name> is ref cursor;
 Create Package pack1
as
Type rear is ref cursor;
End pack1;
Procedure returning multiple rows through OUT parameter.
 Create or replace procedure get_rows(vdept in number, vcur out pack1.rear)
Is
Begin
Open vcur for select empno, ename, sal, job from emp where deptno = vdept;
End;
Using Procedure:
Declare
scur pack1.rear; vroll
number(9); vname
varchar2(90); vfee
number;
Begin
Open scur for select roll, name, fee from student
Where course = ‘&course’;
Loop
Fetch when scur%not found;
DOPL(vroll||’’||vname||’||vfee);
End loop;
Close scur;
End;
Page 48 of 54
PLSQL
9i Features:
9i Joins:
 Supports ANSI/ISO standard sql 1999 syntax.
 Modularity for application sw tools to understand sql queries.
1. Natural Join
2. Join with using Equi Join (giving same output)
3. Join with ON
4. Inner Join
5. Left Outer Join
6. Right Outer Join
7. Full Outer Join  Left outer join union right outer join
8. Cross Join
 Select empno, ename, sal, deptno, dname, loc from emp Natural join dept;
 Select empno, ename, sal, job, deptno, dname, loc from emp join dept using (deptno);
 Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e join dept d on
(e.deptno = d.deptno);
 Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e Inner join dept d
on (e.deptno = d.deptno);
 Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e left outer join
dept d on (e.deptno = d.deptno);
 Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e right outer join
dept d on (e.deptno = d.depno);
 Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e full outer join
dept don (e.deptno = d.deptno);
 Select empno, ename, sal, job, deptno, dname, loc from emp cross join dept;
Date functions:
 Systimestamp:
Gives date and time including rational seconds in SERVER time zone.
 Current_timestamp:
Gives date and time including fractional seconds in CLIENT time zone.
 Sysdate:
Gives only date in server time zone.
 Current_date:
Gives only date in client time zone.
 Extract:
Used to retrieve a particular value from the given date (day/month/year)
 To_timestamp(d):
Converts given date into date and time info with am/pm.
 Dbtimezone:
Gives server time zone value
 Timestamp: Datatype
Automatically stores date and time information with am/pm
Page 49 of 54
PLSQL
 Select systimestamp, current_timestamp from dual;
 Select sysdate, current_date from dual;
 Select dbtimezone from dual;
28-Mar-12 6:50:23 PM
 Select extract(day from sysdate),
Extract(month from sysdate),
Extract(year from sysdate) from dual
 Create table temp(c1 timestamp);
 Insert into temp values(sysdate);
 Select * from temp;
28-Mar-12 6:55:29 PM
NVL:
1. NVL(exp1, exp2):
NVL is used to fill Null value with known value.
If exp1 is NULL value then it will take exp2
If(exp1 = null)
Then expr2
Else
Endif;
Expr1;
2. NVL2(exp1, exp2, exp3):
If expr1 is null it manipulates exp3, if exp1 is not null it manipulates expr2
If(exp1 = null)
Then
Expr3
Else
Endif;
Expr2
Page 50 of 54
PLSQL
MULTIPLE INSERTS:
Supports to insert into more than 1 table at a time but input must be retrieved from existing
table.
EX: Make 3 empty tables same as dept table.
 create table D1 as select * from dept where rownum is null;
 create table D2 as select * from dept where rownum is null;
 create table D3 as select * from dept where rownum is null;
 insert all into D1 values(deptno, dname, loc)
into D2 values(deptno, dname, loc)
into D3 values(deptno, dname, loc)
Select * from dept;
Conditional Insert:
EX-1: Insert all
When (deptno <40) then
Into D1 values(deptno, dname, loc)
When (deptno<90) then
Into D2 values(deptno, dname, loc)
Else
Into D3 values(deptno, dname, loc)
Select * from dept;
EX-2: Insert all
When course = ‘oracle 9i’ then
Into Stu_ora(roll, name, fee)
When course = ‘java’ then
Into stu_java(roll, name, fee)
When course = ‘unix’ then
Into stu_unix values(roll, name, fee)
Select * from student;
MERGE:
 Used to compare the 2 table contents them equal.
 It supports only update & insert operations.
Ex:
Merge
Into temp t
Using emp e
On (t.tno = e.empno)
When matched then
Update set t.sal = e.sal,
t.comm = e.comm,
t.mgr = e.mgr,
t.deptno = e.deptno
Page 51 of 54
PLSQL
when not matched then
insert values(e.empno, e.ename, e.sal, e.com,…
Clauses:
Into --Target
Using --Source
On --join condition
Emp --1 crore rows
Temp --copy of emp -1 crore rows
Emp --5000 inserts & 1000 performed.
Partition Tables:
 Supports to divide the huge tables into multiple partitions logically.
 This will improve the performance while retrieving or updating the data.
Ex:
Create table emp(empno number(4) primary key,----
---------)
Partition by range(empno)
(partition p1 values less than (101),
Partition p2 values less than (201),
Partition p3 values less than (maxvalue));
Insert into emp values(10, ….);  P1 P1 -- 1-100
“ “ (110….); P2 P2 -- 101-200
“ “ (210….); P3 P3 -- 201 – N
“ “ (310,…); P3
 Select * from emp;
 Update emp partition p2 set sal = sal+3000;
 Select * from emp partition p3 where sal > 10000;
 Alter table emp merge partitions (p1, p2);
 Alter table emp drop partition p3;
 Alter table emp add partition p3 values less than (401);
 Alter table emp add partition p4 values less than <maxvalue);
Page 52 of 54
PLSQL
Oracle Utilities:
Performed by the DBA on the dos-Prompt of Server.
3 utilitites….
1. Export:
Used to translate information from database format to OS file format.
EX:
CD:> EXP
Enter username & pwd : scott/tiger
Enter export buffer size(default): Press “enter” key.
Enter export file name: mydata.dmp
Export user(u), table(t) database : T
Export table data : Y
Compress the contents while exporting : Y
Enter table1:emp
Enter table 2:dept
Enter table3: Press “enter” key
2. Import:
Used to translate information from OS file format to database format.
EX:
CD:> IMP
Enter username & pwd : scott/tiger
Enter import buffer size(default): Press “enter” key.
Enter import file name: mydata.dmp
Export entire file : Y
Export table data : Y
List the contents while exporting : N
Ignore error due to object existence : N
3. Sql Loader:
Used to transfer data from OS file to database table.
Step-1:
Abc.txt
10, sales, Hyd
20, import, Pune
30, export, Chennai
40, researc, Bgr
Page 53 of 54
PLSQL
Step-2:
abc.ctl (control file)
Load data
infile abc.txt
insert into table dept
fields terminated by ‘,’
(deptno, dname, loc)
Step-3:
C:>SQLLDR Userid = scott/Tiger control = abc.ctl
NOTE:
 Insert (Default option): Supports
only if table is empty.
 Append: Allows to add the rows
to existing table with data.
 To avoid the abc.ctl.txt(.txt). we
need to put file in “”.
Oracle 10g: [ G  Grid]
Supports “Grid” technology
It is an DBA version
It supports to store “EJB” components directly into database without translation.
It supports with “regular expr’s” to search character data.
It provides high performance compared to other versions.
<<<<<<<<<<<<<<<<<<<<<<<<<<<<< All the Best >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
Don’t Judge a book, by its cover
Page 54 of 54

Weitere ähnliche Inhalte

Was ist angesagt?

Loops in matlab
Loops in matlabLoops in matlab
Loops in matlabTUOS-Sam
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c languagesneha2494
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languagetanmaymodi4
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMMin-Yih Hsu
 
Analyzing ReactOS One More Time
Analyzing ReactOS One More TimeAnalyzing ReactOS One More Time
Analyzing ReactOS One More TimePVS-Studio
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareGagan Deep
 
JavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJanlay Wu
 

Was ist angesagt? (18)

Loops in matlab
Loops in matlabLoops in matlab
Loops in matlab
 
Matlab Script - Loop Control
Matlab Script - Loop ControlMatlab Script - Loop Control
Matlab Script - Loop Control
 
Iteration
IterationIteration
Iteration
 
Looping statements
Looping statementsLooping statements
Looping statements
 
Exception handling
Exception handlingException handling
Exception handling
 
Types of loops in c language
Types of loops in c languageTypes of loops in c language
Types of loops in c language
 
C++ chapter 4
C++ chapter 4C++ chapter 4
C++ chapter 4
 
C# Loops
C# LoopsC# Loops
C# Loops
 
C++loop statements
C++loop statementsC++loop statements
C++loop statements
 
Control statements
Control statementsControl statements
Control statements
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Cpp reference card
Cpp reference cardCpp reference card
Cpp reference card
 
Handling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVMHandling inline assembly in Clang and LLVM
Handling inline assembly in Clang and LLVM
 
Analyzing ReactOS One More Time
Analyzing ReactOS One More TimeAnalyzing ReactOS One More Time
Analyzing ReactOS One More Time
 
C lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshareC lecture 4 nested loops and jumping statements slideshare
C lecture 4 nested loops and jumping statements slideshare
 
4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf4th_Ed_Ch03.pdf
4th_Ed_Ch03.pdf
 
Behavioral modeling
Behavioral modelingBehavioral modeling
Behavioral modeling
 
JavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak TypingJavaScript Loop: Optimization of Weak Typing
JavaScript Loop: Optimization of Weak Typing
 

Ähnlich wie PLSQL

Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Thuan Nguyen
 
Oracle pl sql
Oracle pl sqlOracle pl sql
Oracle pl sqlDurga Rao
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSORArun Sial
 
A Post About Analyzing PHP
A Post About Analyzing PHPA Post About Analyzing PHP
A Post About Analyzing PHPAndrey Karpov
 
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...WebStackAcademy
 
Loops in c language
Loops in c languageLoops in c language
Loops in c languageTanmay Modi
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Béo Tú
 
Verilog Lecture2 thhts
Verilog Lecture2 thhtsVerilog Lecture2 thhts
Verilog Lecture2 thhtsBéo Tú
 
C++ decision making
C++ decision makingC++ decision making
C++ decision makingZohaib Ahmed
 

Ähnlich wie PLSQL (20)

Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
 
Pl sql programme
Pl sql programmePl sql programme
Pl sql programme
 
Cursors
CursorsCursors
Cursors
 
Procedures andcursors
Procedures andcursorsProcedures andcursors
Procedures andcursors
 
Programming in Arduino (Part 2)
Programming in Arduino  (Part 2)Programming in Arduino  (Part 2)
Programming in Arduino (Part 2)
 
Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06Oracle - Program with PL/SQL - Lession 06
Oracle - Program with PL/SQL - Lession 06
 
Oracle pl sql
Oracle pl sqlOracle pl sql
Oracle pl sql
 
PLSQL CURSOR
PLSQL CURSORPLSQL CURSOR
PLSQL CURSOR
 
PLSQL Note
PLSQL NotePLSQL Note
PLSQL Note
 
A Post About Analyzing PHP
A Post About Analyzing PHPA Post About Analyzing PHP
A Post About Analyzing PHP
 
Janakiram web
Janakiram webJanakiram web
Janakiram web
 
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
Core Java Programming Language (JSE) : Chapter IV - Expressions and Flow Cont...
 
Loops in c language
Loops in c languageLoops in c language
Loops in c language
 
Cursors.ppt
Cursors.pptCursors.ppt
Cursors.ppt
 
Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014Verilog Lecture3 hust 2014
Verilog Lecture3 hust 2014
 
Verilog Lecture2 thhts
Verilog Lecture2 thhtsVerilog Lecture2 thhts
Verilog Lecture2 thhts
 
Session 3
Session 3Session 3
Session 3
 
Sqlapi0.1
Sqlapi0.1Sqlapi0.1
Sqlapi0.1
 
C++ decision making
C++ decision makingC++ decision making
C++ decision making
 
Java tut1
Java tut1Java tut1
Java tut1
 

Mehr von Srinath Reddy

Webi Report Function Overview
Webi Report Function OverviewWebi Report Function Overview
Webi Report Function OverviewSrinath Reddy
 
National Education Policy
National Education Policy National Education Policy
National Education Policy Srinath Reddy
 
Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...
Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...
Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...Srinath Reddy
 
Business Objects Designer
Business Objects DesignerBusiness Objects Designer
Business Objects DesignerSrinath Reddy
 

Mehr von Srinath Reddy (7)

Webi Report Function Overview
Webi Report Function OverviewWebi Report Function Overview
Webi Report Function Overview
 
SQL
SQLSQL
SQL
 
Sap Analytics Cloud
Sap Analytics CloudSap Analytics Cloud
Sap Analytics Cloud
 
SAC vs Lumira
SAC vs LumiraSAC vs Lumira
SAC vs Lumira
 
National Education Policy
National Education Policy National Education Policy
National Education Policy
 
Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...
Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...
Tableau - Learning Objectives for Data, Graphs, Filters, Dashboards and Advan...
 
Business Objects Designer
Business Objects DesignerBusiness Objects Designer
Business Objects Designer
 

Kürzlich hochgeladen

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Projectjordimapav
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17Celine George
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designMIPLM
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationRosabel UA
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptxmary850239
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfVanessa Camilleri
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4MiaBumagat1
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataBabyAnnMotar
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Celine George
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 

Kürzlich hochgeladen (20)

Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 
ClimART Action | eTwinning Project
ClimART Action    |    eTwinning ProjectClimART Action    |    eTwinning Project
ClimART Action | eTwinning Project
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17How to Add Barcode on PDF Report in Odoo 17
How to Add Barcode on PDF Report in Odoo 17
 
Keynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-designKeynote by Prof. Wurzer at Nordex about IP-design
Keynote by Prof. Wurzer at Nordex about IP-design
 
Activity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translationActivity 2-unit 2-update 2024. English translation
Activity 2-unit 2-update 2024. English translation
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx4.16.24 Poverty and Precarity--Desmond.pptx
4.16.24 Poverty and Precarity--Desmond.pptx
 
ICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdfICS2208 Lecture6 Notes for SL spaces.pdf
ICS2208 Lecture6 Notes for SL spaces.pdf
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4ANG SEKTOR NG agrikultura.pptx QUARTER 4
ANG SEKTOR NG agrikultura.pptx QUARTER 4
 
Measures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped dataMeasures of Position DECILES for ungrouped data
Measures of Position DECILES for ungrouped data
 
Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17Field Attribute Index Feature in Odoo 17
Field Attribute Index Feature in Odoo 17
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 

PLSQL

  • 1. PLSQL PLSQL Programming Language of Structure Query Language Page 1 of 54
  • 2. PLSQL Features:  Supports to execute a block of commands as a unit.  Supports variables and constants.  Supports conditional constructs.  Supports iteration control statements.  Supports error handling.  Supports to define composite data types.  Supports to execute the code automatically based on the event threw data base triggers.  Supports to store and shared the code using subprograms. PLSQL Block: It is an collection of sql & program language statements. There are 2 types. 1. Anonymous block  Name less block  Temporary block Syntax:- Declare <variable decl> Begin <exec stmts>; End; 2. Named Block  Block with fixed name.  Stored permanently in database Ex:- Subprograms. Variable declaration:  All sql data types are supported.  Boolean is supported. Declare Veno number(4):=7900; Vename varchar2(90); Vjob varchar2(90) NOTNULL :=’CLERK’; Doj date default sysdate; Flag Boolean:= TRUE; Pin constant number(6):=500038; := Assignment operator = Comparission operator Executable Statements:  DML and TCL are not valid.  DDL and DCL are not allowed. Page 2 of 54
  • 3. PLSQL  Select ----- into statement.{ Used to retrieve data into Plsql variables.} Select <column list> into <variables> from <table name> Where <condition>;  Used to print message & variables contents onto screen. DBMS_OUTPUT.PUT_LINE(‘message Text’ || Variables);  Comments --Comment line /*Multi Line Comment*/  Activates the DBMS stmt output buffer. >set server output on; Ex: Plsql Program retrieves the employ details and calculates the net salary and prints. Declare Veno number(4):=3400; or &employ; Vname varchar2(90); Vsal number(12,2); Vcomm number(12,2); Net number(12,2); Begin --Retrieve data from table. Select ename, sal, comm. Into vname, vsal, vcomm from emp Where empno=veno; --Calculated net salary Net:= vsal+nvl(comm., 0); Dbms_output.put_line(‘employ details are:’||veno||’’||vename||’’||net); End; / To save to local system(.sql file) Save <filename> To display the file Get filename To open the file in editor Ed filename To execute the file Start filename or @filename Page 3 of 54
  • 4. PLSQL Attribute Declaration: Used to define the Plsql variables dynamically according to the table structure. 1. %Type: Column type declaration. Used to define the variables according to the specific column structure. Syntax: variable <tablename>.<columnname>%type; Ex: Declare --using %type declaration Veno emp.empno%type := &employ; Vsal emp.sal%type; Vcomm emp.comm%type; Net emp.sal%type; 2. %Rowtype: Record type declaration Used to define the variables according to the complete table structure. Syntax: variable <tablename>%rowtype; Ex: declare --using %Rowtype declaration. I emp%rowtype; Net number(19,9); Begin i.empno :=&empno; select ename, sal, comm. Into i.ename, i.sal, i.comm from emp where empno = i.empno; net:= sal+nvl(comm., 0); dbms_output.put_line(‘Employ details are:’||i.empno||’’||i.ename||’’||net); end; / Page 4 of 54
  • 5. PLSQL Conditional Constructs: Used to check for multiple conditions while manipulating data in plasql 1. If 2. case(8i) 1. Simple If If <condition 1> then <exec stmts>; Elsif <cond 2> then <exec stmts>; -- -- Else < exec stmts>; End if; Ex: Plsql block checks for existing new comm. And assign new comm.. Declare Veno emp.empno%type := &employ; Vname emp.ename%type; Vcomm emp.comm%type; Begin Select ename, comm. Into vname, vcomm from emp Where empno = veno; If vcomm is null then Vcomm :=3000; Elsif vcomm = 0 then Vcomm :=2500; Else vcomm := vcomm+vcomm*.25; Endif; Update emp set comm.= vcomm wehre empno = veno; Dbms_output.put_line(veno||’’||vname|’’||vcom); Commit; End; / 2. Case(8i) : o Used to check for multiple conditions easily. o It will check for equality condition. o It can be used in “select” statement Syntax: 1. Case <variable> When <value1> then <exec stmts>; When <value2> then <exec stmts>; -- -- Page 5 of 54
  • 6. PLSQL -- Else <exec stmts> End case; 2. Case When <cond1> then <value1> When <cond2> then <value2> Else <value> End case; Using case construct: Ex: Declare Grade char(1):=’&grade’; Begin Case grade When ‘A’ then Dbms_output.put_line(‘Grade is A’); When ‘B’ then Dbms_output.put_line(‘Grade is B’); When ‘C’ then Dbms_output.put_line(‘Grade is C’); Else Dbms_output.put_line(‘Grade is C’); End case; End; / Case in select: select empno, ename, sal, job, case when job = ‘CLERK’ then ‘C’ when job = ‘salesman’ then ‘B’ when job in (‘Manager’, ‘Analyst’) then ‘B+’ when job = ‘President’ then ‘A’ else ‘D’ end “Grade” from emp; --It is used to generate reports. Page 6 of 54
  • 7. PLSQL Iteration control statements: (LOOPS) Supports to execute a block of stmts until conditions are true. 4 types: 1. simple loop 2. while loop 3. numeric for loop 4. cursor for loop 1. Simple Loop: It is an infinite loop block. Syntax: Loop <exec stmts<; End loop; To break simple loop : o Exit when(cond); o If(cond) then Exit; End if; Ex: --Prints first 10 numbers onto screen Declare A number(3):= 1; Begin Dbms_output.put_line(‘The numbers are:’); Loop Dbms_output.put_line(‘a’); A := a+1; Exit when (a > 10); End loop; Dbms_output.put_line(‘End of numbers’); End; / 2. While Loop: It is an pre-tested loop. Syntax: While (cond) Loop <exec stmts>; End loop; Ex: Declare A number(3):=1; Begin Dbms_output.put_line(‘The numbers are:’); While (a<=10) loop Dbms_output.put_line(‘a’); Page 7 of 54
  • 8. PLSQL A := a+1; End loop; Dbms_output.put_line(‘End of numbers’); End; / 3. Numeric For Loop: It increments the variable by 1 always. Variable can’t be assigned with a value in for loop. Syntax: For <var> in [reverse] <value1>..<value2> Loop <Exec stmts>; End loop; <var> –Automatically defined by for loop. Reverse(optional) –Accepts values in reverse order .. –Range operator Ex: Begin Dbms_output.put_line(‘The numbers are:’); For n in 1..10 Loop Dbms_output.put_line(n); End loop; Dbms_output.put_line(‘end of numbers); End; Dbms_output.put : prints the results in same line. Dms_output.put_line : prints the result in new line. Put_line must be followed with “put” stmt to activate output buffer. 4. Cursor For loop: Used to perform cursor operations automatically Improves performances Syntax: For <var> in <cur name> Loop <exec stmts>; End loop; Advantages: No need to open cursor No need to fetch rows No need to check for end of rows No need to close cursor No need to declare variables Ex: Declare Cursor c2 is select * from dept; Begin For I in c2 Page 8 of 54
  • 9. PLSQL Loop Dbms_output.put_line(c2%rowcount||’’||i.deptno||’’||i.dname||’’||i.loc); End loop; --close cursor End; Declare Cursor ecur Is For I in c2 loop Declares I variable Open cursor Fetch 1 row into i Check end of rows Select empno, ename, sal, job, emp.deptno, dname, loc From Emp, dept Where emp.deptno = dept.deptno; Page 9 of 54
  • 10. PLSQL CURSORS:  It is a temporary buffer used to hold the transaction data for manipulation purpose.  It is not stored in database.  It is not re-usable.  It is valid in Plsql block only.  It is created in logical memory only. 2 types A. implicit cursors:  Automatically defined by oracle whenever “DML” operations are performed by user.  It has a fixed name “SQL”  It gives the status of DML statements in Plsql block.  It will not support cursor operations.  It supports %found, %nofound, %rowcount, attributes. Ex: TO update only 5 employees Declare Vdno number(2) := &dno; Begin Update emp set sal = sal+1000 where deptno = vdno; If sql%notfound then Dbms_output.put_line(‘Unable to update rows –No such dept exists’); Elsif sql%rowcount > 5 then Dbms_output.put_line(‘ Invalid operation –Can’t update more than 5 employees’); Rollback; Else Dbms_output.put_line(sql%rowcount||’ employees are updated successfully’); Commit; End if; End; / B. Explicit cursors: Created by user in Plsql block used to retrieve multiple rows into Plsql block for manipulation purpose. 1. Declaring cursor: Syntax : cursor <cur name> is <select stmt>; 2. Cursor Operations: i. Open cursor: Open <cur name>; Used to open the cursor. Memory will be allocated to cursor after opening it. Page 10 of 54
  • 11. PLSQL ii.Fetch Cursor: Fetch <cur name> into <var’s>; Used to retrieve data from cursor to Plsql variables. At a time it can retrieve only one row into variables Generally fetch will be placed in loop iii.Close Cursor: close <cursor name>; Used to close the cursor. Memory allocated will be de-allocated. 3. Cursor Attributes: Gives the status of cursor <cur name>%<attribute> i. %isopen (Returns true/false) Returns True if cursor is opened successfully ii. %found (Returns true/false) Returns True if fetch stmt successfully retrieves the into Plsql var’s. iii. %notfound (Returns true/false) Returns true if fetch stmt fails to retrieve the row into Plsql var’s. iv. %rowcount (Returns true/false) Returns the no of rows successfully retrieved from cursor so far. Initially it holds 0. After every successful fetch it is incr by 1. Ex-1: Declaring cursor var with %Type Declare Cursor c1 Is Select empno, ename, comm. From emp Order by deptno; Veno emp.empno%type; Vname emp.ename%type; Vcomm emp.sal%type; Begin Open c1; If c%isopen then Dbms_output.put_line(‘EMP NEW COMM’); LOOP Fetch c1 into veno, vname, vcomm; Exit when c1%notfound; If vcomm is null then Vcomm := 3000; Elsif vcomm = 0 then Vcomm := 2500; Else vcomm := vcomm+vcomm*.25; Endif; Update emp set comm.= vcomm where empno = veno; Page 11 of 54
  • 12. PLSQL Dbms_output.put_line(veno||vname||vcomm); End loop; Dbms_output.put_line(c1%rowcount||’Employees are updated with new comm’); Close c1; Commit; Else dbms_output.put_line(‘Unable to open cursor’); End if; End; / Declaring cursor var with rowtype. Ex-2: Declare Cursor c2 Is select * from dept; I c2%rowtype; Begin Open c2; Loop Fetch c2 into I; Exit when c2%notfound; Dbms_output.put_line(c2%rowcount||’’||i.deptno||’’||i.dname||’’||i.loc); End loop; Close c2; End; Cursor with Scalar query: Ex1: Declare Cursor c2 is select eno, ename, sal ,job, (select min(sal) from emp where job = e.job) lopay, (select max(sal) from emp where job = e.job) hipay, from emp E order by job; Begin For k in c2 Loop Dbms_output.put_line(k.eno||’’||k.job||’’||k.ename||’’||k.sal||’’||k.lopay||k.hipay); End loop; End; / Ex2: Calculate bonus for first 10 lowest employees. Declare Cursor c1 Is Select eno, ename, sal, sal+nvl(comm., 0) net, job from emp Order by sal; I c1%rowtype; Page 12 of 54
  • 13. PLSQL Bonus emp.sal%type; Begin For I in c1 Loop If i.job = ‘CLERK’ Then bonus:= round(i.net*.25); Elsif i.job = ‘EXECUTIVE’ Then bonus := round(i.net*.50); Else then Bonus := round(i.net*.1); End if; Dbms_output.put_line( i.eno||’’||i.ename||’’||i.job||’’||bonus); Exit when(c1%rowcount >= 10); End loop; End; / Cursor with Parameters(8.0):  Used to accept the input dynamically while opening the cursor.  Supports to define generalized cursor.  Maximum 32 parameters can be passed to cursor. Ex-1: Calculates incr for employees depending on experience for particular dept only. Declare Cursor c1(dno number) Is Select * from emp Where deptno = dno; I c1%rowtype; Incr number(12); Expr number(2); Begin Open c1(&dno); Loop Fetch c1 into i; Exit when c%notfound; Net := i.sal + nvl(comm., 0); Expr := round(months_between(sysdate, i.hiredate))/12); If expr <=2 Then incr := net*.25; Elsif expr<=5 Then incr := net*.5; Else incr := net*.1; End if; Update emp set sal := sal+incr where eno = i.eno; Page 13 of 54
  • 14. PLSQL Dbms_output.put_line(i.eno||’’||e.job||’’||expr||incr||i.deptno); End loop; Close c1; End; / EX-2 : Cursor c2(dno number, vjob varchar2) Is select * from emp Where deptno = dno and job = vjob; Open c2(30, ‘clerk’); For I in c2(20, ‘salesman’) loop Ex-3: Cursor c3(vcourse varchar2, vtime varchar2) Is select * from student where course = vcourse and timing = vtime; open c3(‘oracle 9i’, ’10AM’); for I in c3(‘oracle 9i’, ‘6PM’); EX-4: Cursor c4 Is select * from student Where course = &course’; It is valid in oracle sql environment. Cursor parameters are used to pass values from other application s/w tools. Page 14 of 54
  • 15. PLSQL EXCEPTIONS:  Errors in Plsql block are termed as exceptions.  Error handling solutions are provided in exception block. 3 types… 1. Pre defined exceptions Defined by oracle Activated by oracle automatically. Solution provided by user.  No_data_found: Automatically activated whenever select stmt fails to retrieve data into variables.  Too_many_rows: Automatically activated whenever select stmt retrieves more than one row into variables.  Value_Error: Automatically activated whenever data types are not matching.  Zero_divide: Automatically activated whenever invalid arithmetic operations is performed (no/zero).  Dup_val_on_index: Automatically activated whenever duplicate values are inserted into unique index column.  Storage_error: Automatically activated whenever there is lack of memory in server.  Invalid_cursor: Automatically activated whenever user fetch the rows from cursor without opening the cursor.  Time_out_on_resoursces: Automatically activated whenever user performs an infinite loo process.  Transaction_backed_out: Automatically activated whenever there is an communication problem with server.  Login_denied: Automatically activated whenever user name or pwd are not valid.  Cursor_already_open: Automatically activated whenever user opends the cursor which is already in open state.  Others: General exception Used to handle any pre-defined exception. It will not support non-predefined/user defined exceptions. Pseudo columns activated by other exception. It must be last exception in exception block. SQLCODE: Holds the currently raised error no. SQLERRM: Holds the currently raised error message. Page 15 of 54
  • 16. PLSQL 2. User defined exceptions  Defined by user.  Activated by using “RAISE” stmt.  Solution provided by user. Ex: Plsql block handles diff types of errors. Declare Veno emp.eno%type := &employ; Vname emp.ename%type; Vsal emp.sal%type; Salary_missing exception; --Declaring user defined excep Begin Select ename, sal into vname, vsal from emp Where eno = veno; If vsal is null then Raise salary_missing; --Activating user defined excep Else vSal := vsal + vsal * .5 Update emp set sal = vsal where eno = veno; Dbms(‘salary updated for’||veno||’is’||vsal); Commit; End if; When no_data_found then Dbms_output.put_line(‘No such emp found’||veno); when too_many_rows then dbms_output.put_line(‘More than one emp found for’||veno); when salary_missing then dbms_output.put_line(‘Emp has null salary –providing default pay’); update emp set sal=5000 where eno= veno; commit; when others then dbms_output.put_line(‘Error occurred’); dbms_output.put_line(sqlcode||’’||sqlerrm); end; / 3. Non pre-defined exceptions (undefined exceptions)  Defined by user.  Activated automatically by constraints.  Solution provided by user.  Used to handle constraint violation of errors in Plsql. Ex: Handling foreign key constraint error. Declare Vdno number(2) := &dno; Employ_exists exception; Page 16 of 54
  • 17. PLSQL Pragma exception_init(employ_exists, -2292); Begin Delete from dept where dno = vdno; Commit; Exception When employ_exists then Dbms_output.put_line(‘ Emp are still working –can’t remove dept’); End; / EXCEPTION_INIT(Exception_name, Error_no); Built-in sub-pgm used to provide exception name to the constraint violation error EXCEPTION PROPAGATION: Declare ------- ------- Begin ------- ------- Begin ------- ERR ------- ------- Exception ------- ------- ------- Solution End; No Solution ------- ------- Exception ------- Sol No sol ------- Quit with error ------- Quit with success End; / Page 17 of 54
  • 18. PLSQL PRAGMA: It is an special instruction to Plsql to execute sub program in declaration section. DEPT EMP -- -- -- -- Deptno(PK) eno Deptno(FK) Constraint violation error no’s: -00001 Unique -1400 Not null -2290 Check -2291 Parent not exists(ref) -2292 Child records exists(ref) EX-1: create table std_inf(roll number(4), name varchar2(90), course varchar2(20) check( course in (‘oracle 9i’, ‘unix’, ‘D2k’)), fee number); Insert into std_inf values( 101, ‘Sai’, ‘java’, 2300); PLSQL block handling check constraint error Declare Invalid_course exception; Pragma exception_init(invalid_course, -2290); Begin Insert into std_inf values(101, ‘Sai’, ‘java’, 2300); Commit; Exception When invalid_course then Dbms_output.put_line(‘ student course must be oracle 9i or unix or d2k’); End; / EX-2: Using nested blocks, cursors with lock and exceptions. Create table itemmast(itno number(2), name varchar2(90), qoh number(4), rol number(5)); Insert into itemmast values(&1, ‘&2’, &3, &4); Create table ittran(itno number(4), tran_type char(1) [I-Issue(-), R-Receipts(+)], qty number(5), updt char(1)); Insert inot ittran values(&1, ‘&2’, &3, ‘&4’); Declare Cursor tran is select into, tran_type, qty from ittran where upper(updt) = ‘N’ for update; Cursor item is select * from itemmast; Vname varchar2(20); Vqoh number(4); --cursor with lock Page 18 of 54
  • 19. PLSQL Begin For I in tran loop Begin --nested loop Select name, qoh into vname, vqoh from itemmast Where itno = i.itno; Exception When no_data_found then Dbms_output.put_line(‘no such item exists with itno’||itno); End; If i.tran_type = ‘R’ then Vqoh := vqoh + i.qty; Elsif i.tran_type = ‘I’ then Vqoh := vqoh – i.qty; End if; Update itemmast set qoh = vqoh where itno = i.itno; Update ittran set updt= ‘Y’ where CURRENT OF TRAN; End loop; Commit; Dbms_output.put_line(‘Stock Report’); For k in item loop Dbms_output.put_line(k.itno||’’||k.name||’’||k.qty); End loop; Exception When others than Dbms_output.put_line(sqlcode||’’||sqlerrm); End; FOR UPDATE: Locks the rows retrieved into cursor WHERE CURRENT OF: Clause (8.0) Used to locate the current row manipulated by cursor To use this cursor must be locked Page 19 of 54
  • 20. PLSQL Composite data types: [User defined data types]  Defined by the user.  Valid in Plsql block only.  They are not stored in the database permanently.  They will not hold data.  They are not re-usable.  This will improve performance of oracle while retrieving or manipulating huge loads of data into Plsql blocks. 2 types… 1. PLSQL Records: It is an collection of elements of “different data types” stored at one location. It is similar to “C Prog” structures. Syntax: Type <record name> is record (element1 <datatype>, Element2 <datatype>, ….. Elementn <datatype>); EX: Declare --declaring Plsql record. Type erec is record(eid number(4), name emp.ename%type, basic emp.sal%type, da emp.sal%type, hra emp.sal%type, e.pf emp.sal%type, gross emp.sal%type); E erec; --record type variable Begin e.eid:= &employ; select ename, sal into e.name, e.basic from emp where empno = e.eid; e.da := e.basic*.24; e.hra:= e.basic*.15; e.pf:= e.basic*.15; e.gross := e.basic+e.da+e.hra-e.pf; dbms_output.put_line(e.eid||’’||e.name||’’||e.basic||’’||e.pf||’||e.gross); end; 2. PLSQL Tables: It is an collection of elements of same datatype stored in continous memory locations. It is similar to “C Prog” arrays. It is supported with an index automatically. Syntax: Type <table_name> is table of <datatype> index by binary_integer; Page 20 of 54
  • 21. PLSQL EX: Declare --declaring Plsql tables. TYPE names IS TABLE OF emp.ename%type INDEX BY BINARY_INTEGER; TYPE pays IS TABLE OF emp.sal%type INDEX BY BINARY_INTEGER; N names; P pays; Totsal number(12) := 0; Ctr number(9):=1; Begin --filling tables For I in (select ename, sal from emp) loop N(ctr):= i.ename; P(ctr):=i.sal; Ctr:= ctr+1; End loop; --printing table contents For k in 1..n.count loop Dbms_output.put_line(n(k)||’’||p(k)); Totsal:= totsal + p(k); End loop; Dbms_output.put_line(‘Total Salary is :’||totsal); End; N.COUNT : Gives no of elements in Plsql table Page 21 of 54
  • 22. PLSQL Nested records and Plsql tables using records: Declare Type pf_rec is record(pfno number(9), amt number(12,2)); --Nested record Type erec is record(eid number(9), name emp.ename%type, basic emp.sal%type, job emp.job%types, pf pf_rec); Type etab is table of erec Index by binary_integer; Ctr number(3):=1; E etab; Begin --plsql table using nested records. For I in (select empno, ename, sal, job from emp) pf.rec Loop E(ctr).eid := i.empno; erec E(ctr).name := i.ename; E(ctr).job := i.job; etab E(ctr).pf.pfno := i.empno+1000; E(ctr).pf.amt := round(i.sal * .15); Ctr := ctr + 1; End loop; --printing table contents Dbms_output.put_line(‘employee pay details are:’); For k in 1..e.count Loop Dbms_output.put_line(e(k).eid||’’|| e(k).name||’’|| e(k).basic||’’|| e(k).job||’’|| e(k).pf.pfno||’’|| e(k).pf.amt); End loop; End; / Page 22 of 54
  • 23. PLSQL DATABASE TRIGGERS:  A set of Plsql stmts stored permanently in database and automatically activated whenever an event raising stmt (DML) is preformed.  They are stored in user_triggers system table.  They are use to impose business rules/user defined restrictions on table.  They are also activated when tables are manipulated by either users or by other application s/w tools.  They provide high security on tables.  TCL commands are not allowed in triggers. Trigger parts: 1. Triggering even: Indicates when to activate the trigger. Before – insert/update/delete After – insert/update/delete 2. Trigger types: a. Row trigger: Activates the trigger for every row manipulated by DML stmt. b. Stmt trigger: Activates the trigger for only once for 1 DML stmt (Default type). 3. Trigger restriction: Used to stop the activation of trigger based on condition. If condition is true trigger is active. 4. Trigger Body: A set of Plsql stmts. Syntax: Create or replace TRIGGER <trigger_name> Before/after insert or update or delete (1) [of <columns>] on <table_name> [for each row (2) When (<condition>) (3) Declare <var declaration>; ] If condition is true trigger is activated Begin <exec stmts>; [Exception <exec stmts>;] End; Page 23 of 54
  • 24. INSERT UPDATE DELETE NEW valid valid invalid OLD invalid valid valid PLSQL EX: Trigger converts student name to upper case automatically. Create ore replace trigger up_con before insert on stu_info For each row Begin :new.sname := upper(:new.sname); End; Triggering Events: 12 Events per table are allowed. NEW & OLD (pseudo columns):  Used to retrieve data from DML stmt tempory buffer.  Valid with “ROW” triggers only. Before insert row before update row before delete row Before insert stmt before update stmt before delete stmt After insert row After update row After delete row After insert stmt After update stmt After delete stmt EX: Trigger checks fro valid increment. Create or replace trigger valid_incr Before update of sal on emp For each row Begin If :new.sal <= :old.sal then Column specification is supported with update event only. Not valid with insert and delete. operations(Row level operations) Raise_application_error(-20300, ‘Incr must be more than existing salary’; End if; End; / Raise_application_error(error no, error message); Built in subprogram stops DML stmt execution and displays the error message. Error_NO range: -20002 to -20990 Oracle Reserved error no’s: -20000 to +20000 Page 24 of 54
  • 25. PLSQL Constraints vs Triggers:  Constraint provide standard error message.  Triggers provide user friendly error message.  Constraints will for existing errors.  Triggers will not check for existing errors.  If constraint & trigger are defined on table, one time only trigger will be activated. Ex: Trigger checks for valid salary according to the job. Create table job_pays(job varchar2(20), losal number(10), hisal number(10)); Create or replace trigger chk_sal Before insert on emp for each row When(new.job<>’PRESIDENT’) --If true trigger is activated Declare Minsal number(10); Maxsal number(10); Begin Select losal, hisal into minsal, maxsal from job_pays Where job =:new.job; If :new.sal>maxsal and :new.sal<minsal then Raise_application_error(-20201, ‘salary must be between’||maxsal||’and’||minsal||’for job’||:new.job); End if; Exception When no_data_found then Raise_application_error(-20202, ‘No data found for dept’||:new.job); End; / EX: Trigger adds the fee installment amt automatically into fee installments table Create fee_installments(roll number(9), prev_fee number(9), curr_fee number(9), dop date); Create or replace trigger add_fee Before update or insert on student For each row Begin If inserting then Keywords: Inserting, updating, deleting Represents insert, update, delete operations. Valid in triggers only Insert into fee_installments values(:new.roll, :new.fee, :new.fee, sysdate); Elsif updating then Insert into fee_installments values(:old.rol, :old.fee, :new.fee - :old.fee, sysdate); End if; End; / Page 25 of 54
  • 26. PLSQL Statement level triggers:  Trigger locks the table for DML operations to provide security.  Trigger checks for o Valid timings o Weekends o Public holidays Ex: Create or replace trigger security_chk Before insert or update or delete on bankmaster Declare A number; Begin --check for valid timings. If to_char(sysdate, ‘hh24’) not in (10,11,12,13,14,15,16,17,18) then Raise_application_error(-20111, ‘No operations allowed –invalid timings’); End if; --check for week ends. If to_char(sysdate, ‘dy’) in (‘sat’,’sun’) then Raise_applicaiton_error(-20112, ‘No operations allowed –week ends’); End if; --check for public holidays Select count(*) into a from holiday where to_date(hdate) = to_date(sysdate); If a>0 then Raise_application_error(-20113, ‘No operations allowed –public holidays’); End if; End; / Instead of triggers:  Triggers supported only on “views”  Used to perform DML operations on “join views” Instead of ----insert, update, delete EX: Create view edept As Select empno, ename, job, sal, emp.dtno, dept.dtno dno, dname, loc from emp, dept Where emp.dno = dept.dno; Create trigger T1 instead of insert on edept For each row Begin Insert into dept values(:new.dno, :new.dname, :new.loc); Insert into emp(empno, ename, sal, job, dtno) values(:new.empno, :new.ename, :new.sal, :new.job, :new.dtno); End; Page 26 of 54
  • 27. PLSQL Disabling triggers: Alter table <table_name> disable all triggers; Enabling triggers: Alter table <table_name> enable all triggers; Removing triggers: Drop trigger <trigger_name>; Checking for existing triggers:  Desc user_triggers;  Select trigger_name, trigger_event from user_triggers Where table_name = ‘emp’;  Select * from user_triggers Where trigger_name = ‘chk_sal’ Create trigger T2 Before insert on temp for each row Begin Update temp set c2 = ‘HARI’; End; --It will not perform update in trigger body because 2 DML operations can’t be performed on table at once --It leads to a trigger mutation error while working in other s/w tools. Page 27 of 54
  • 28. PLSQL SUBPROGRAMS:  A set of Plsql stmts stored permanently database and used to perform a task.  They can accept input from user as arguments dynamically.  They are stored in “user_source” system table.  They are reusable components.  They can be shared with other users.  They can be used n other application s/2 tools.  They are faster in execution stored n compiled formed.  They support modularity. 2 types… 1. Procedures 2. Functions A huge task divided into N no of sub tasks. Easy to manage the logic easy to debug errors. 1.Procedures:  A sub prg type performs a task and will return a value.  Generally procedures are used to perform DML operations on database.  They can’t be called in SELECT stmt.  Procedure can be used in sql, other application s/w tools, Plsql triggers procedures, functions, packages, D6i. Syntax: Create or replace procedure <p_name> [(arguments MODE <datatype>)] Is [<var_declaration>] Begin EX: End; <exec stmts>; Calling a procedure: procedure_name(arguments); Create or replace procedure Sim_ins(p number, n number, r number) Is Si number(12); Begin Si := (p*n*r)/100; Dbms_output.put_line(‘simple interest:’||si); End; / SQL: PLSQL: Desc sim_ins begin Exec sim_ins(2,3,4); sim_ins(123,12,8.5); End; Page 28 of 54
  • 29. PLSQL 2.Functions:  A sub prog type performs a task and will return the value (Return only one value).  Generally functions are used for reporting purpose or for calculating purpose.  They can be called in SELECT stmt.  Function can be used in sql, select, other application tools, Plsql, triggers, procedures, functions, packages. Syntax: Create or replace function <function_name> [(arg’s MODE <datatype>)] Return <datatype> Is [<var declaration>]; Begin <exec stmts>; Return (variable); [Exception <exec stmts>;] End; Calling a function: var := fun_name(arg’s); EX: Create or replace function si(p number, n number, r number) Return number Is Si number(9); Begin Si := (p*n*r)/100; Return(round(si)); End; SQL: PLSQL: i. Desc si Declare Select si(1200,8,7) from dual; result number(12); begin ii. Variable result number result:=si(1200,9,7); exec:result:=si(5400, 10, 9.5); dbms_output.put_line(result); print result; end;  Create table loan_master(cust_id number(4), cname varchare(9), amount number(12), duration number(3), irate number(5,2));  Insert into loan_master values(&1, ‘&2’, &3, &4, &5);  Select cust_id, upper(cname), si(amount, duration, irate) interest from loan_master; Page 29 of 54
  • 30. PLSQL EX-1: Function checks for leap year Create or replace function chk_year(y number) Return varchar2 Is Begin If mod(y,4) = 0 then Return(‘leap year’); Else End if; End; Return (‘ Not leap year’); Select chk_year(2008), chk_year(2010) from dual; Variable result varchar2(90); Exec:result:=chk_year(2012); Print result; SET AUTOPRINT ON Automatically prints the variable, No need to use print stmt. EX-2: Procedure cal the new comm. For all emp of particular dept. Create or replace procedure call_comm(vdept number) Is Cursor c1 Is Select empno, ename, comm. From emp Where deptno = vdept; I c1%rowtype; Begin For I in c1 Loop If i.comm is null Then i.comm :=3000; elseif i.comm = 0 then else end if; i.comm:=2500; i.comm = i.comm+i.comm*.25; update emp set comm. = i.comm where empno = i.empno; dbms_output.put_line(i.empno||’has been updated comm. For’||i.comm); end loop; commit; end; Page 30 of 54
  • 31. PLSQL  Desc user_source  Select name from user_source; To Remove sub prog’s:  Drop procedure <proc_name>;  Drop function <fun_name>;  Create sequence s1 increment by 1 start with 11; EX-3: Procedure adds a dept into Dept table Create or replace procedure add_dept (vname varchar2 default ‘unknown’, vloc varchar2 default ‘hyderabad’) Is Begin Insert into dept values(s1.nextval, vname, loc); Commit; End;  Desc add_dept  Exec add_dept;  Exec add_dept(‘sales’, ‘mumbai’);  Exec add_dept(‘export’);  Exec add_dept(vloc => ‘chennai’);  Exec add_dept(vloc=> ‘pune’, vname => ‘software’); Sharing Sub-Programs: Scott:  Grant execute on add_dept to user1; User1:  Desc scott.add_dept  Exec scott.add_dept(‘Testing’); Named notation: Arguments are passed based on their name.  Insert into scott.dept values(22, ‘HR’, ‘sec’); --Error User can manipulate the table only through procedure but not directly. Parameter modes in sub-programs: “MODE” indicates the behaviour of argument in sub program 3 types…. 1. IN: (default mode)  IN parameter is used to carry the input into subprogram.  It can’t be assigned with a value in subprogram. Page 31 of 54
  • 32. PLSQL 2. OUT:  OUT parameter is used to return the results from sub program.  It can’t be assigned with a value in sub program 3. IN OUT:  INOUT parameter is used to carry the input and return the results from subprogram.  It can be assigned with a value in subprogram. EX-1: Create or replace procedure P1(a in out number) Is Begin A:= A*A*A; End; SQL:  Desc p1  Var x2 number;  Exec :x2 := 5; --intialising variable at sql  Exec p3(:x2);  Print x2 EX-2: Calculate factorial for given number and checks for odd/even number. Create or replace function call_fact( n in number, f out number); Return Boolean Is Fac number(9) :=1; Begin For I in 1..n Loop Fac := fac * I; End loop; -- cal factorial 5! = 5*4*3*2*1 =120 F:= fac; -- storing result in out parameter If mod(n,2) = 0 Then Else End if; End; Return(TRUE); Return(false); Function returning “Boolean” value (or) with OUT parameter can’t be used in sql or select stmt. Using “CALL_FACT” function: Declare A number(9) := &num; Fact number(90); Begin Page 32 of 54
  • 33. PLSQL If call_fact(a, fact) Then Else End if; Dbms_output.put_line(‘Given number is even’); Dbms_output.put_line(‘Given number is odd’); Dbms_output.put_line(‘Factorial of given number is:’||fact); End; Triggers vs Programs:  Triggers are automatically activated by DML statements.  Procedures & functions has to be explicitly activated by user. Advantages:  Code reusability.  Faster execution of code.  Easy to manage code.  Executed in the oracle server memory even if it is activated from other application software tools. Page 33 of 54
  • 34. PLSQL PACKAGES:  It is a collection of related var’s, cursors, procedures and functions.  It is stored in “user_source” system table.  It can be shared with other users.  They will improve performance of oracle while accessing sub programs from client environment.  They support oops features live encapsulation, data hiding, and function over loading. 2 parts… i. package specification: It holds the declaration of variables, cursors, procedures and functions. Syntax: Create or replace package Package_name As <Var dec>; Procedure <proc_name>(arg’s datatype); Functions <fun_name>(arg’s datatype) return datatype; End <pack_name>; ii. Package body: it holds the code of sub program. Syntax: Create or replace package body Package_name As Procedure <proc_name>(arg’s datatype) Is <exec stmts>; End <proc_name>; Functions <fun_name>(arg’s datatype) return datatype Is <exe stmts>; End <fun_name>; End <pack_name>; Ex-1: Create or replace package pack1 as result number(12) procedure add_num( a number, b number); function mul_num(x number, y number); end pack1; create or replace package body pack1 as procedure add_num(a number, b number) is begin result := a+b; Page 34 of 54
  • 35. PLSQL dbms_output.put_line(‘sum of numbers is:’||result); end add_num; function mul_num(x number, y number) return number is begin result := x*y; return (round(result)); end mul_num; end pack1; / Using package elements:  Exec pack1.add_num(2099, 8908);  Select pack1.mul_num(200,22) from dual;  Select ename, job, pack1.mul_num(sal,.15) pf, pack1.mul_num(sal, 2) bonus from emp; EX-2: LOCAL sub program are valid in package body only. Create or replace package epack As Function gross(vsal number) return number; Function experience(doj date) return number; End epack; Create or replace package epack As Function pf(vbasic number) return number is Begin Return( round(vbasic*.15)); End if; Function gross(vsal number) return number is Epf number(12); Begin Epf := pf(vsal); Return (round(vsal+vsal * .25 + vsal*.35 – epf)); End gross; Function experience (doj date) return number is Begin Return (round(months_between(sysdate, doj))/12); End experience; End epack; / Sub-program not defined in specification are local sub programs. We can’t call this pgm’s from outside of package. Select empno, ename, job, round(epack.experience(hiredate) experience, epack.gross(sal) “Gross pay” from emp; Select ename, epack.pf(sal) “PF” from emp; Page 35 of 54
  • 36. PLSQL --ERROR, you can’t call local subprogram. Package with function overloading feature: Create or replace package load_pack As Function add_data(a number, b number) return number; Function add_data(a varchar2, b varchar2) return varchar2; End load pack; / Create or replace package load_pack body As Function add_data(a number, b number) return number Is Begin Return (a+b); End add_data; Function add_data(a varchar2, b varchar2) return number Is Begin Return(a||’ ‘||b); End add_data; End load_pack; / Removing Pack:  Desc load_pack;  Select load_pack.add_data(5,6) total, load_pack.add_data(‘Satya’, ‘M’) name from dual;  Drop package <pack_name>; Sharing Pack:  Grant execute on load_pack to user1; To view existing package body:  Select text from user_source wehre name = ‘pack1’; Page 36 of 54
  • 37. PLSQL 8.0 Features: Returning into clause: o Used to return the values through “DML” stms. o Used with update and delete stmts. Ex:  Var a varchar2(20)  Var b number  Update emp set sal = sal+3000 where empno = 7900 Returning ename, sal, into :a, :b;  Print a b  Delete from emp where mepno= 7920 Returning ename, sal into :a, :b;  Print a b Bulk Collect: o Used to return bulk data into Plsql variables o Variables must be of Plsql table type only o Improves performance while retrieving data. o Used with select, update, delete, fetch stmts. Examples: Using in select stmt:  Declare Type names table of emp.ename%type Index by binary_integer; Type pays table of emp.sal%type Index by bindary_integer; N names; P pays; Begin --Retrieving all emp’s in 1 transaction Select ename, sal bulk collect into N, P from emp; --Printing table contents Dbms_output.put_line(‘Employ details are’); For I in 1..n loop Dbms_output.put_line(n(i)||’’||p(i)); End loop; End; Using in update stmt:  Update emp set sal=sal+3000 where deptno = 30 Returning ename, sal bulk colleck into n,p; Using in delete stmt:  Delete form emp where job = ‘CLERK’ Returning ename, sal bulk collect into n,p; Page 37 of 54
  • 38. PLSQL Using in fetch stmt:  Declare Type names is table of emp.ename%type Index by binary_integer; Type names is table of emp.sal%type Index by binary_integer; N names; P pays; Cursor c1 is Select ename, sal into n, p from emp; Begin Open c1; Fetch c1 bulk collect into n,p; --printing table contents For I in 1..n count Loop Dbms_output.put_line(n(i)||’’||p(i)); End loop; End; / Dynamic SQL: o Supports to execute DDL commands in Plsql block. Execute immediate(‘DDL stmt’); EX:  Begin Execute immediate(‘create table employ(ecode number, ename varchar2(90), sal number)); End;  Begin Execute immediate(‘drop table employ1’); End; NOTE: Table can’t be manipulated in same Plsql block. Using Long and Raw data types: Long: o Used to represent numbers or character values o Maximum limit is 2GB. o But only once it can be used in table. Raw(n): o Used to represent images o Max limit is 256 bytes(7.0)/2000 bytes (8.0) Long Raw: o Used to represent images upto 2 GB. o Raw and long raw can be manipulated by GUI tools only Page 38 of 54
  • 39. PLSQL Ex:  Create table emp(ecode number(3), ename varchar2(20), sal number(12,2), description long, deptno number(2));  Create table ephoto(ecode number(4), photo long raw);  Create table customer(cust_id number(4), cname varchar2(20), addr varchar2(50), photo longraw); File input & output (8.0):  Used to transfer oracle table contents to OS file and OS file content to oracle table.  Standard package holds all functions (arthematic, date, general); UTL_FILE  Built in package supports file operations. Sub-Programs in UTL_FILE pkg:  Fopen: Used to open the file in the specified mode and returns the address of the file. Mode R  Read, W  Write, A  Append  Fclose: Used to close the file  Get_line: Used to read a line from file to Plsql variable.  Put: Used to write a line into file but in New line.  Put_line: Used to write a line into file but in new line.  Fflush: Writes the file content from temporary buffer to physical memory (saving file into OS)  File_type: Data type Used to define the variable to hold the address of file.  Invalid_file_handle, Read_error: Pre-defined exception automatically activated while working with files. Plsql block transfers data from oracle table to OS file. Ex: Plsql procedure transfer data from OS file to database table. Create or replace procedure load_student(pdir varchar2, pfile varchar2) Is Vfile utl_file.file_type; Vtext varchar2(200); Vname varchar2(20); Vcourse varchar2(20); Vfee number(5); Fcomma number(3); Scomma number(4); Begin Vfile:= utl_file.fopen(pdir, pfile, ‘R’); Page 39 of 54
  • 40. PLSQL Loop Begin Utl_file.get_line(vfile, vtext); Exception When no_data_found then Exit; End; Fcomma := instr(vtext, ‘,’,1,1); Scomma := instr(vtext, ‘,’, 1,2); Vname := substr(vtext,1,fcomma,-1); Vcourse:=substr(vtext, fcomma+1, soma-fcomma); Vfee := substr(vtext, scomma+1); Insert into student values(s1.nextval, vname, vcourse, vfee); End loop; Commit; Exception When utl_fjile.read_error then Dbms_output.put_line(‘unable to read the file….’); End;  Exec load_student(‘c:’, ‘student.txt’): Note: Provide the below parameter in “init.ora” file (open in notepad) UTL_FILE_DIR = ‘C:Oracleora92Bin’ Init.ora --system parameter file. Holds the parameter defined for oracle server. Page 40 of 54
  • 41. PLSQL Object Technology(8.0):  Object is a collection of different datatypes stored at one location.  It will not hold data  It can have methods (functions) defined in it.  They are stored permanently in “user_types” system table  They support inheritance feature.  They can be shared with other users.  They are reusable components. CDT: (composite data type)  Object  ‘C’ structure  Object with methods  ‘C++’ class  Nested tables  Varying arrays EX: Plsql records Plsql tables Syntax: Create type <obj name> as object (element1 <datatype>, ele 2 <datatype>, ------ Element N <datatype>); Object types: 2 types… 1. Column object: Only few columns of table represent objects. 2. Row Object: Entire table structure depends on object.  Create type etype as object( eid number(9), ename varchar2(90), sal number, deptno number(9));  Create table etab of etype;  Row object  Desc etab = desc etype  Insert into etab values(1001, ‘RAM’, 210,10);  Select * rom etab;  Select eid, ename, sal from etab;  Create table employ(einfo etype, job varchar2(90), hiredate date);  Column object Ex:  Create type addr_type as object (hno varchar2(90), street varchar2(90), city varchar2(90), pin number(6));  Create type Pf_type as object (pfno number(5), amt number(4));  Desc addr_type;  Desc pf_type;  Select * form user_types; Page 41 of 54
  • 42. PLSQL Naming object:  Create table student(roll number(3), sname varchar2(20), address addr_type, course varchar2(90), fee number(5));  Desc student;  Insert into student values(101, ‘SAI’, addr_type(’12-A’, ‘ameerpet’, ‘Hyd’, 500038), ‘oracle 9i’, 2500);  Select * from student;  Select sname, address from student;  Select sname, s.address.city, s.address.pin from student s;  Update student s set s.address.hno = ‘308A’ where roll=101;  Delete from student s where s.address.city = ‘hyd’; Objects will not support constraints. Trigger check for null values in city. Create trigger city_chk before insert on emp for each row begin if :new.address.hno is null then Raise_aplication_error(-20100, ‘Student hno can’t be null’); End if; End; Sharing object: Scott: Grant execute on addr_type to user1; User1:  Create table supplier(sid number, sname varchar2(90), saddr scott.addr_type);  Select sname s.saddr.city from supplier s Nested objects: [Max 32 levels]  Create type person_type as object(pname vachar2(20), paddr addr_type);  Desc person_type;  Create table customer(cid number, cinfo person_type);  Select cid, c.cinfo.paddr.city, c.cinfo.paddr.pin from customer c;  Desc customer;  Drop type <obj_name>;  Drop type addr_type;  Drop type pf_type; Purity level test:  Checks for member functions are having DML stmts or not.  DML are not valid in member functions. Page 42 of 54
  • 43. PLSQL Restrict_references: Built-in sub program used to check for DML stmts in methods WNDS: Write no database state Pragma: Instruction to Plsql supports to execute sub program in declaration section Object with methods:  Create or replace type etype as object(ecode number, name varchar2(90), basic number(90), job varchar2(4), hiredate date, member function gross(vbasic number) return number, pragma restrict_references(gross, WNDS), member function experience(doj date) return number, Pragma restrict_references(experience, WNDS));  Create or replace type body etype as Member function gross(vbasic number) return number Is Begin End; Return(round(vbasic+vbasic*.25+vbasic*.35-vbasic*.15)); Member function experience(doj date) return number Is Begin End; End; Return(round(months_between(sysdate, doj))/12);  Create table etab of etype;  Row object  Insert into etab values(1001, ‘RAM’ 3000, ‘Analyst’, ’10-dec-01’);  Select ecode, name, job, basic, e.gross(basic) “gross”, e.experience(hiredate) “exp in years” from etab e; Page 43 of 54
  • 44. PLSQL Collections(8.0):  A group of similar rows stored at one location. 2 types… 1. Nested table:  Table with in a table  A column holds a table of contents in it. Ex:  Create type book_type as object (bookid number(4), title varchar2(90), doi date, dor datae); Object representing table of books  Create type books is table of book_type;  Create table stu_lib(roll number, name varchar2(90), course varchar2(90), binfo books) nested table binfo store as book_table;  Desc book_type;  Desc books;  Desc stu_lib;  Insert into stu_lib values(101, ‘RAM’, ‘Oracle 9i’, books(book_type(11, ‘sql’, sysdate, sysdate+10), book_type(12, ‘plsql’, sysdate, sysdate+11), book_type(13, ‘dba’, sysdate, sysdate+15)));  Select * from stu_lib;  Select name, binfo from stu_lib; Roll Name Course Binfo 101 102 Book id Title Doi Dor 11 12 13 2. Varrying arrays examples:  It is an array of elements stored in a column. EX: i. Create type blist is varray(5) of varchar2(25); --Object representing array of books. ii. Create table items(itno number, name varchar2(90), brands blist); iii. Insert into items values(102, ‘Micro-oven’, blist(‘LG’, ‘ONIDA’, ‘IFB’)); iv. desc blist desc items Page 44 of 54
  • 45. PLSQL v. update items set brands = blist(‘LG’, ‘ONIDA’, ‘IFB’, ‘KENSTAR’, ‘SAMSUNG’) where itno = 102; vi. select name, brands from items; BINFO Roll Name Course Bid Title Doi dor 101 11 12 13 102 Nested table Varray Stored outside the table Stored with in the table DML is allowed DML is not allowed Stores unlimited data stores limited data. Note:  Collections will not support constraints  Long, raw, lob data types are not valid in collections.  Collections will not support dev-6i, VB (GUI tools)  Java supports collections. DML on nested tables: THE: Operator is used to perform DML on nested table. EX: Inserting a book(only 1 book allowed)  Insert into THE(select binfo from stud_lib where roll=101) Values(book_type(15, ‘DBA’, sysdate, sysdate+10)); Changing a book details  Update  Update THE(select binfo from stu_lib where roll = 101) Set dor=sysdate+3 where book_id = 12; THE(select binfo from stu_lib where roll=101) Set title=’Tuning’ where book_id = 15; Removing a book info  Delete from THE(select binfo from stu_lib where roll=101) Where book_id =12; Page 45 of 54
  • 46. PLSQL LOBS – Large Objects(8.0):  Used to represent huge loads of fdata  Max limit is 4 GB  N columns allowed per table 4 types… 1. CLOB – Char Large Object Used to represent char information upto 4 GB. 2. NCLOB – Native char large object Used to represent other language text. *Nchar, Nvarchar2 -- Represents other language test. 3. BLOB – Binary large object Used to represent images upto 4GB. 4. BFILE – Binary File Used to hold the address of OS file. Representing Null values: CLOB - Empty_CLOB( ) NCLOB- Empty_NCLOB( ) BLOB - Empty_BLOB( ) BFILE - Skip the column while inserting EX: Create table emp_lob(ecode number, name varchar(90), description CLOB, sal number, photo BLOB, edocs BFILE); Making logical dir to insert Bfile value: DBA > Grant create any directory to scott; SCOTT > Create directory emp_dir as ‘C:employbonds’; > Insert into emp_lob values (101, ;’RAM’, ‘………’, 2100, empty_BLOB( ), Bfilename(emp_dir, ‘e101.doc’)); Built in subprogram used to represent OS file details into bfile > Select ecode, ename, sal, description from emp_lob; Page 46 of 54
  • 47. PLSQL Temparary Tables(8i):  Used to hold the information in logical memory but not in physical memory.  They hold the data for a particular period of time but not permanently. EX-1:  Create global temporary table temp(c1 date) on commit delete rows;  Insert into temp values(sysdate);  Select * from temp; --28-Mar-2012  Commit;  Select * from temp; -- No rows. EX-2:  Create global temporary table(c1 date) on commit preserve rows;  Insert into temp values(sysdate);  Select * from temp; --28-Mar-2012  Commit;  Select * from temp; --28-Mar-2012  Exit;  Select * from temp; --No rows. Autonomous Transactions:  Defines the trigger as an independent transaction  Allows TCL commands in triggers. Syntax: Create trigger add-incr before insert on incr For each row Declare Pragma autonomous transaction; Update emp set sal = sal+ :new.amt Where empno = :new.empno; Commit; End;    Select empno, sal from emp; Insert into incr values(7900, 4000); Select empno, sal from emp; --7900 8000 --7900 12000    Select empno, amt from incr; Rollback; Select empno, amt from incr; --7900 4000 --No rows  Select empno, sal from emp; --7900 12000 Page 47 of 54
  • 48. PLSQL REF CURSORS: Dynamic Cursors:  Supports to define the cursor without select stmt.  Select stmt will be provided while opening cursor.  Used to send cursor as an parameter in sub programs.  Made easy to transfer huge data through sub programs. Syntax: Type <ref cursor name> is ref cursor;  Create Package pack1 as Type rear is ref cursor; End pack1; Procedure returning multiple rows through OUT parameter.  Create or replace procedure get_rows(vdept in number, vcur out pack1.rear) Is Begin Open vcur for select empno, ename, sal, job from emp where deptno = vdept; End; Using Procedure: Declare scur pack1.rear; vroll number(9); vname varchar2(90); vfee number; Begin Open scur for select roll, name, fee from student Where course = ‘&course’; Loop Fetch when scur%not found; DOPL(vroll||’’||vname||’||vfee); End loop; Close scur; End; Page 48 of 54
  • 49. PLSQL 9i Features: 9i Joins:  Supports ANSI/ISO standard sql 1999 syntax.  Modularity for application sw tools to understand sql queries. 1. Natural Join 2. Join with using Equi Join (giving same output) 3. Join with ON 4. Inner Join 5. Left Outer Join 6. Right Outer Join 7. Full Outer Join  Left outer join union right outer join 8. Cross Join  Select empno, ename, sal, deptno, dname, loc from emp Natural join dept;  Select empno, ename, sal, job, deptno, dname, loc from emp join dept using (deptno);  Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e join dept d on (e.deptno = d.deptno);  Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e Inner join dept d on (e.deptno = d.deptno);  Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e left outer join dept d on (e.deptno = d.deptno);  Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e right outer join dept d on (e.deptno = d.depno);  Select e.empno, e.ename, e.sal, e.job, e.deptno, d.dname, d.loc from emp e full outer join dept don (e.deptno = d.deptno);  Select empno, ename, sal, job, deptno, dname, loc from emp cross join dept; Date functions:  Systimestamp: Gives date and time including rational seconds in SERVER time zone.  Current_timestamp: Gives date and time including fractional seconds in CLIENT time zone.  Sysdate: Gives only date in server time zone.  Current_date: Gives only date in client time zone.  Extract: Used to retrieve a particular value from the given date (day/month/year)  To_timestamp(d): Converts given date into date and time info with am/pm.  Dbtimezone: Gives server time zone value  Timestamp: Datatype Automatically stores date and time information with am/pm Page 49 of 54
  • 50. PLSQL  Select systimestamp, current_timestamp from dual;  Select sysdate, current_date from dual;  Select dbtimezone from dual; 28-Mar-12 6:50:23 PM  Select extract(day from sysdate), Extract(month from sysdate), Extract(year from sysdate) from dual  Create table temp(c1 timestamp);  Insert into temp values(sysdate);  Select * from temp; 28-Mar-12 6:55:29 PM NVL: 1. NVL(exp1, exp2): NVL is used to fill Null value with known value. If exp1 is NULL value then it will take exp2 If(exp1 = null) Then expr2 Else Endif; Expr1; 2. NVL2(exp1, exp2, exp3): If expr1 is null it manipulates exp3, if exp1 is not null it manipulates expr2 If(exp1 = null) Then Expr3 Else Endif; Expr2 Page 50 of 54
  • 51. PLSQL MULTIPLE INSERTS: Supports to insert into more than 1 table at a time but input must be retrieved from existing table. EX: Make 3 empty tables same as dept table.  create table D1 as select * from dept where rownum is null;  create table D2 as select * from dept where rownum is null;  create table D3 as select * from dept where rownum is null;  insert all into D1 values(deptno, dname, loc) into D2 values(deptno, dname, loc) into D3 values(deptno, dname, loc) Select * from dept; Conditional Insert: EX-1: Insert all When (deptno <40) then Into D1 values(deptno, dname, loc) When (deptno<90) then Into D2 values(deptno, dname, loc) Else Into D3 values(deptno, dname, loc) Select * from dept; EX-2: Insert all When course = ‘oracle 9i’ then Into Stu_ora(roll, name, fee) When course = ‘java’ then Into stu_java(roll, name, fee) When course = ‘unix’ then Into stu_unix values(roll, name, fee) Select * from student; MERGE:  Used to compare the 2 table contents them equal.  It supports only update & insert operations. Ex: Merge Into temp t Using emp e On (t.tno = e.empno) When matched then Update set t.sal = e.sal, t.comm = e.comm, t.mgr = e.mgr, t.deptno = e.deptno Page 51 of 54
  • 52. PLSQL when not matched then insert values(e.empno, e.ename, e.sal, e.com,… Clauses: Into --Target Using --Source On --join condition Emp --1 crore rows Temp --copy of emp -1 crore rows Emp --5000 inserts & 1000 performed. Partition Tables:  Supports to divide the huge tables into multiple partitions logically.  This will improve the performance while retrieving or updating the data. Ex: Create table emp(empno number(4) primary key,---- ---------) Partition by range(empno) (partition p1 values less than (101), Partition p2 values less than (201), Partition p3 values less than (maxvalue)); Insert into emp values(10, ….);  P1 P1 -- 1-100 “ “ (110….); P2 P2 -- 101-200 “ “ (210….); P3 P3 -- 201 – N “ “ (310,…); P3  Select * from emp;  Update emp partition p2 set sal = sal+3000;  Select * from emp partition p3 where sal > 10000;  Alter table emp merge partitions (p1, p2);  Alter table emp drop partition p3;  Alter table emp add partition p3 values less than (401);  Alter table emp add partition p4 values less than <maxvalue); Page 52 of 54
  • 53. PLSQL Oracle Utilities: Performed by the DBA on the dos-Prompt of Server. 3 utilitites…. 1. Export: Used to translate information from database format to OS file format. EX: CD:> EXP Enter username & pwd : scott/tiger Enter export buffer size(default): Press “enter” key. Enter export file name: mydata.dmp Export user(u), table(t) database : T Export table data : Y Compress the contents while exporting : Y Enter table1:emp Enter table 2:dept Enter table3: Press “enter” key 2. Import: Used to translate information from OS file format to database format. EX: CD:> IMP Enter username & pwd : scott/tiger Enter import buffer size(default): Press “enter” key. Enter import file name: mydata.dmp Export entire file : Y Export table data : Y List the contents while exporting : N Ignore error due to object existence : N 3. Sql Loader: Used to transfer data from OS file to database table. Step-1: Abc.txt 10, sales, Hyd 20, import, Pune 30, export, Chennai 40, researc, Bgr Page 53 of 54
  • 54. PLSQL Step-2: abc.ctl (control file) Load data infile abc.txt insert into table dept fields terminated by ‘,’ (deptno, dname, loc) Step-3: C:>SQLLDR Userid = scott/Tiger control = abc.ctl NOTE:  Insert (Default option): Supports only if table is empty.  Append: Allows to add the rows to existing table with data.  To avoid the abc.ctl.txt(.txt). we need to put file in “”. Oracle 10g: [ G  Grid] Supports “Grid” technology It is an DBA version It supports to store “EJB” components directly into database without translation. It supports with “regular expr’s” to search character data. It provides high performance compared to other versions. <<<<<<<<<<<<<<<<<<<<<<<<<<<<< All the Best >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> Don’t Judge a book, by its cover Page 54 of 54