Sei sulla pagina 1di 64

PLSQL

? Introduction to PLSQL
Level 1 - Blocks
? Named Blocks
? Un Named Blocks (Anonymous Blocks)
Level 2 - Data Types
? % Type
? % Row Type
? PL/SQL Record
? PL/SQL Table
? Index By Table
Level 3 - Control Statements
? If
? If Else
? Elsif
? CASE
Level 4 - Loops
? Simple Loop
? While Loop
? For Loop
Level 5 - Cursors
? Implicit Cursor
? Explicit Cursor
? Parameter Cursor
? Ref Cursor
Level 6 - Exceptions
? Pre Defined Exceptions
? User Defined Exceptions
? Non Predefined Exceptions
Level 7 - Procedures
? Normal Procedures
? Procedure with Parameters
? Procedure Overloading
Level 8 - Functions
? Normal Funtions
? Function with Parameters
? Function Overloading
Level 9 - Packages
? Package Body
? Package Specification
Level 10 - Triggers
? Data Base Triggers
? DML Triggers
Level 11 - Collections
? Varrays
? Nested Tables
? Plsql Tables

Level 12 - Bulk Operations


? Bulk Collect
? Bulk Bind
Level 13 - Pragma
? Pragma Exception
? Pragma Autonamous Transaction
? Mutating Trigger
------PL/SQL
------It is a programming language which is used to define
It is used execute block of statements at a time and
It supports variables and conditional statements and
It supports object oriented programming and supports
It supports handle the error handling mechanism.

our own logics.


increase the performance.
loops.
composite data types.

*************************************************************************
-----Block
------->It is one of the area which is used to write a Programming logic.
-->Block has 3 sections:
1. Declaration Section:
** It is one of the section which is used to declare variables, cursors and exce
ptions and so on.
** It is Optional Section.
2. Executable Section
** It is one of the Section which is used to write a Program Coding.
** It is Mandatory Section.
3. Exception Section
** It is one of the Section which is used to handle the errors at runtime.
** It is Optional Section.
There are Two Types of blocks Supported by PL/SQL
1. Anonymous Block:
** These blocks do not have a name and also not stored in the Database.
Ex1: DECLARE
_______________
BEGIN
------------END;
Ex2: BEGIN
DBMS_OUTPUT.PUT_LINE("Welcome to E Busin
ess Solutions");
END;
2. Named Block:
** These blocks are having a name and also s
tored in database.
Examples : Procedures , Functions, Packages and Triggers etc..

Variable
-->It is one of the memory location which is used to store the d
ata.
-->Generally we declare the variables in declaration section.
-->Variables Support default and not null.
Syntax :Variable_Name

Datatype ( Size );

Ex : Declare
A
Number (5);
B
Number (5) not null :=10;
C
Number (5) default 10;
Ex-1 :
Declare
A Varchar2(20);
Begin
A := Hello EBS ;
Dbms_Output.Put_Line( A );
End;
=>Storing a value into variable:
Using assignment operator ( := ) we storing a value into
variable.
Syntax : Variable_Name := value;
Ex : a :=50;
=>Display Message ( or ) Varaible Value:
We have one pre defined package which is used display th
e message or value in a program.
Syntax : dbms_output.put_line ( message );
dbms_output.put_line ( variable_name );
=>Select ------ Into ------ Clause:
This clause is used to retrieve the data from table & st
oring into pl/sql variables.
Syntax : select col1, col2 into var1, var2;
*************************************************************************
---------DataTypes
---------1. % Type
2. % RowType
3. RecordType ( or ) Pl/sql Record
4. IndexBy Table ( or ) Pl/sql Table (COLLECTIONS) VVIP *******
%Type:
-->It is one of thedatatype which is used to assign the column datatype to a var
iable.
-->It is used to storeone value at a time.
-->It is not possibleto hold more than one column values or row values.
Syntax : variable_name table_name.column_name%type; Ex-1 :
Declare
Vno
emp.empno%type:=&n;
Vname emp.ename%type;
Begin

Select
ename into vname from emp where empno=vno;
Dbms_output.put_line (
employee name is :
End;

||

|| vname );

% RowType
-->It is one of the datatype which is used assign all the column datatypes of ta
ble to a variable.
-->It holds entire record of the same table.
-->Each of the time it override only one record.
-->It is not possible to capture more than one table data.
Syntax :variable_name table_name%rowtype;
Ex-1 :
Declare
Vrow
emp%rowtype;
Vno
emp.empno%type:=&n;
Begin
Select * into vrow from emp where empno=vno;
Dbms_output.put_line ( vrow.ename ||
|| vrow.sal );
End;
Record Type ( or ) Pl/Sql Record
-->Is is one of the user defined temporary data type which is used to store more
than one table data ( or ) to assign more than one column datatypes.
-->They must at least contain one element.
-->Pinpoint of data is not possible.
Syntax : Type Typename is Record ( Val-1 Datatype, Val-2 Datatype, ..);
Var Typename
Ex : Declare
Type Rec is record ( vname emp.ename%type,
Vsal emp.sal%type,
VLoc dept.loc%type);
Vrec Rec;
Vno emp.empno%type:=&n;
Begin
Select ename,sal,loc into vrec from emp,dept where emp.deptno=dept.deptno and em
p.empno=vno;
Dbms_output.put_line(vrec.vname|| , ||vrec.vsal|| , ||vrec.vloc);
End;
*************************************************************************
----------------------Conditional Statements
----------------------1.
2.
3.
4.

If Condition
If Else Condition
Elsif Condition
Case Condition

=>If Condition:

Syntax :
If condition then
Statements;
End if;
Ex-1 :
Declare
A Number ( 4 ) :=&n;
B
Char ( 1 );
Begin
If a<20 then
B:= Yes ;
End if;
Dbms_output.put_line ( B );
End;
=>If Else Condition:
Syntax :
If condition then
Statements ;
Else
Statements ;
End if;
Ex-1 :
Declare A Number ( 4 ) :=&n;
B Char ( 10 );
Begin
If a<20 then
B:= TRUE ;
Else
B:= FALSE ;
End if;
Dbms_output.put_line ( B );
End;
=>Elsif Condition
Syntax :
If condition-1 then
Statements;
Elsif condition-2 then
Statements;
Elsif condition-3 then
Statements;
Else
Statements;
End if;
Ex-1 :
Declare A Number ( 4 ) :=&n;
B
Char ( 15 );
Begin
If a<20 then
B:= Low Value ;
Elsif a>20 and a<100 then
B:= High Value ;
Else

B:= Invalid Value ;


End if;
Dbms_output.put_line ( B );
End;
=>Case Condition:
Syntax :
Case ( column name )
When condition then
Statements;
When condition then
Statements;
Else
Statements;
End Case;
Ex-1 :
DECLARE
VSAL NUMBER(10):=&N;
BEGIN
CASE
WHEN VSAL<2000 THEN
DBMS_OUTPUT.PUT_LINE('VSAL IS'||' '||'LOW');
WHEN VSAL>2000 THEN
DBMS_OUTPUT.PUT_LINE('VSAL IS'||' '||'HIGH');
ELSE
DBMS_OUTPUT.PUT_LINE('VSAL IS'||' '||'INVALID');
END CASE;
END;
*************************************************************************
-----Loops
-----1.
2.
3.
4.

Loop
Simple Loop
While Loop
For Loop

=>Simple Loop:
Syntax :
Loop
Statements;
End loop;
Syntax :
Loop
Code;
Exit when condition;
End loop;
Ex-1 :
Begin
Loop
Dbms_output.put_line (

Welcome to k-onlines.com' );

End loop;
End;
Ex-2 :
Declare
N
number(5):=1;
Begin
Loop
Dbms_output.put_line ( n );
Exit when n>=10;
N:=n+1;
End loop;
End;
Ex-3 :
Declare
N number(5):=1;
Begin
Loop
Dbms_output.put_line ( n );
If n>=10 then
Exit;
End if;
N:=N+1;
End loop;
End;
=>While Loop:
Syntax :
While ( Condition )
Loop
Statements;
End loop;
Ex-1:
Declare
N Number(4):=1;
Begin
While n>=10
Loop
Dbms_output.put_line ( N );
N:=N+1;
End loop;
End;
=>For Loop:
Syntax :
For variable_name in
Loop
Statements;
End loop;
Ex-1:
Declare
N number(5);
Begin

lowerbound..outerbound

For
n in 1..10
Loop
Dbms_output.put_line ( N );
End loop;
End;
Ex-2
Declare
N number(5);
Begin
For
n in reverse 1..10
Loop
Dbms_output.put_line ( N );
End loop;
End;
*************************************************************************
------------------------BIND VARIABLE/SESSION VARIABLE/HOST VARIABLE---------------------------------------------------------------------------------------------------------->These Variables are Session Variables
Syntax: Variable a Number;
Ex-1 :
Variable V Number;
DECLARE
A Number(5):=500;
BEGIN
:v:=a/2;
END;
*************************************************************************
-------CURSOR
--------->Cursor is a buffer area which is used to process Multiple records and also re
cord by record process
There are Two Types of Cursors:
1. Implicit Cursor
2. Explicit Cursor
=> IMPLICIT CURSOR :
1. SQL Statements return a single record
is called implicit cursor
2. Implicit cursor operations done by Sy
stem
3. Open by the system.
4. Fetch the records by the system.
5. Close the cursor by the system.
Eg:

DECLARE
X EMP%ROWTYPE;
BEGIN
SELECT * INTO X FROM EMP WHERE EMPNO=736
9;
DBMS_OUTPUT.PUT_LINE(X.EMPNO||','||X.ENA
ME);
END;
=> EXPLICIT CURSOR :
1. SQL Statements return a multiple reco
rd is called Explicit cursor
2. Explicit cursor operations done by th
e user.
3.
4.
5.
6.

Declare by user.
Open by the user.
Fetch the records by the user.
Close the cursor by the user.

Eg1:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
CLOSE C1;
END;
//will print only one record, 1st record.
Eg2:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
END LOOP;
CLOSE C1;
END;
//Will print all records
, but finaly record will go on infinite loop until buffer overflow as we have no
t specified exit loop considtion. We use Cursor attributes to specify the exit l
oop condition while using cursor.
Eg3:

DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
FETCH C1 INTO V_NAME,V_SAL;
DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
CLOSE C1;
// Will print 2 records, as we have fetched twice without using loop.
END;

--> CURSOR ATTRIBUTES:


-------------------> Every explicit cursor has four cursor attrib
utes.
1.
2.
3.
4.

%NotFound
%Found
%IsOpen
%RowCount

--> All the attributes are used along with curso


r name
syntax: cursorname % cursorattribute
--> All cursor attribute except %RowCount, will
return boolean value either TRUE or FALSE, where as %RowCount will return Number
datatype, it will return the number of row count.
A) %NOTFOUND:
----------> Returns
rsor is declared, but not open or if cursor is closed.
--> Returns
EN, but fetch has not been executed
--> Returns
ll fetch has been executed
--> Returns
eturned

INVALID_CURSOR if cu
NULL if cursor is OP
FALSE if a successfu
TRUE if no row was r

Eg:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
V_NAME VARCHAR2(10);
V_SAL NUMBER(10);
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO V_NAME,V_SAL;
EXIT WHEN C1%NOTFOUND;

DBMS_OUTPUT.PUT_LINE(V_NAME||','||V_SAL)
;
END LOOP;
CLOSE C1;
END;
Eg2:
DECLARE
CURSOR C1 IS SELECT ENAME, SAL FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO VROW.ENAME,VROW.SAL;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(VROW.ENAME||','||VR
OW.SAL);
END LOOP;
CLOSE C1;
END;
//same as above program, but here we are using single variable of rowtype datayp
e.
B) %FOUND:
----------> Returns
rsor is declared, but not open or if cursor is closed.
--> Returns
EN, but fetch has not been executed
--> Returns
l fetch has been executed
--> Returns
returned

INVALID_CURSOR if cu
NULL if cursor is OP
TRUE if a successful
FALSE if no row was

Eg1:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO VROW.EMPNO, VROW.ENAME, VR
OW.SAL;
IF C1%FOUND
THEN
DBMS_OUTPUT.PUT_LINE(VROW.ENAME||','||VR
OW.ENAME||','||VROW.SAL);
ELSE
EXIT;
END IF;
END LOOP;
CLOSE C1;
END;
C) %IsOpen:

----------> Returns TRUE if the cursor i


s Open.
--> Returns FALSE if the cursor
is closed.
Eg1:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS OPEN");
LOOP
FETCH C1 INTO VROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(VROW.ENAME||','||VR
OW.ENAME||','||VROW.SAL);
END LOOP;
END IF;
CLOSE C1;
IF NOT C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS CLOSED")
;
END IF;
END;

D) %ROWCOUNT:
----------> Returns INVALID_CURSOR if cu
rsor declared but not open or if cursor is closed.
--> Returns the number of rows f
etched by the cursor.
Eg1:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS OPEN");
LOOP
FETCH C1 INTO VROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(VROW.ENAME||','||VR
OW.ENAME||','||VROW.SAL);
END LOOP;
END IF;
DBMS_OUTPUT.PUT_LINE("Total Number of Em
ployees:" || C1%ROWCOUNT);
CLOSE C1;
IF NOT C1%ISOPEN THEN

DBMS_OUTPUT.PUT_LINE("CUROSR IS CLOSED")
;
END IF;
END;

Eg2:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
VROW EMP%ROWTYPE;
BEGIN
OPEN C1;
IF C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS OPEN");
LOOP
FETCH C1 INTO VROW;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(C1%ROWCOUNT||','||V
ROW.ENAME||','||VROW.ENAME||','||VROW.SAL);
END LOOP;
END IF;
DBMS_OUTPUT.PUT_LINE("Total Number of Em
ployees:" || C1%ROWCOUNT);
CLOSE C1;
IF NOT C1%ISOPEN THEN
DBMS_OUTPUT.PUT_LINE("CUROSR IS CLOSED")
;
END IF;
END;

--> PARAMETER CURSOR :


-------------------Passing a Parameter to a cursor is called as P
arameter cursor.
Syntax:
declare cursor cursor_name(parameter_nam
e) IS Select * from table_name where coloumn_name:=parameter_name;
Eg1:
DECLARE
Cursor c1(p_deptno number) is select * from emp
where deptno=p_deptno;
I emp%rowtype;
BEGIN
Open c1(10);
LOOP
fetch c1 into i;
exit when c1%notfound;
dbms_output.put_line(i.empno||','||i.ename||','|
|i.job);
end loop;
close c1;
end;

Ex2:
DECLARE
Cursor c1(p_job varchar2) is select * from emp w
here job=p_job;
I emp%rowtype;
BEGIN
Open c1('MANAGER');
LOOP
Fetch c1 into i;
Exit when c1%notfound;
DBMS_OUTPUT.PU_LINE(i.empno||','||i.ename||','||
i.job);
End LOOP;
Close c1;
Open c1('CLERK');
LOOP
Fetch c1 into i;
exit when c1%notfound;
dbms_output.put_line(i.empno||','||i.ename||','|
|i.job);
end loop;
close c1;
end;
Ex3:
DECLARE
Cursor c1(p_job varchar2,p_deptno number) is sel
ect * from emp where job=p_job and deptno=p_deptno;
I emp%rowtype;
BEGIN
Open c1(&p_job , &p_deptno);
LOOP
Fetch c1 into i;
Exit when c1%notfound;
DBMS_OUTPUT.PUT_LINE(i.empno||','||i.ename||','|
|i.job);
End LOOP;
Close c1;
Open c1(&p_job , &p_deptno);
LOOP
Fetch c1 into i;
exit when c1%notfound;
dbms_output.put_line(i.empno||','||i.ename||','|
|i.job);
end loop;
close c1;
end;
--> CURSOR WITH FOR LOOP:
---------------------- In cursor for Loop no need to opne, fetch and
close cursor. For loop will automatically do all of these operations.
Eg1:
DECLARE

CURSOR C1 IS SELECT * FROM EMP;


I EMP%ROWTYPE;
BEGIN
FOR I IN C1 LOOP
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||I.ENA
ME);
END LOOP;
END;
--> NESTED CURSOR WITH FOR LOOP:
---------------------------Eg1 :
DECLARE
CURSOR C1 IS SELECT * FROM DEPT;
CURSOR C2 IS SELECT * FROM EMP;
BEGIN
FOR I IN C1
LOOP
DBMS_OUTPUT.PUT_LINE(I.DEPTNO);
END LOOP;
FOR J IN C2
LOOP
DBMS_OUTPUT.PUT_LINE(J.EMPNO||','||J.ENA
ME||','||J.SAL);
END LOOP;
END;
Eg2:
DECLARE
CURSOR C1 IS SELECT * FROM DEPT;
CURSOR C2(P_DEPTNO NUMBER) IS SELECT * F
ROM EMP WHERE DEPTNO=&P_DEPTNO;
BEGIN
FOR I IN C1
LOOP
DBMS_OUTPUT.PUT_LINE(I.DEPTNO);
FOR J IN C2(I.DEPTNO)
LOOP
DBMS_OUTPUT.PUT_LINE(J.EMPNO||','||J.ENA
ME||','||J.SAL);
END LOOP;
END LOOP;
END;
--> CURSOR WITH DML OPERATION:
-------------------------Eg1 :
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
BEGIN
FOR I IN C1
LOOP
INSERT INTO T1

VALUES(I.ENAME,I.SAL);
END LOOP;
END;
Eg2:
DECLARE
CURSOR C1 IS SELECT * FROM CURSOR_TABLE;
BEGIN
FOR I IN C1
LOOP
DELETE FROM CURSOR_TABLE WHERE EMPNO BET
WEEN 7900 AND 8000;
END LOOP;
END;
Eg3:
DECLARE
CURSOR C1 IS SELECT * FROM EMPLOYEES;
BEGIN
FOR I IN C1
LOOP
IF I.JOB='CLERK'
THEN
UPDATE EMPLOYEES SET SAL=SAL+1111 WHERE
EMPNO=I.EMPNO;
ELSIF I.JOB='MANAGER'
THEN
UPDATE EMPLOYEES SET SAL=SAL+2222 WHERE
EMPNO=I.EMPNO;
END IF;
END LOOP;
END;

--> Ref CURSOR:


------------Ref cursors are user define types which is use
d to process multiple records and also this is record by record process.
--Generally through the static cursors we are us
ing only one select statement at a time for single active set area where as
in Ref cursors we are executing no of select
statements dynamically for single active set area.
--Thats why these type of cursors are also calle
d as dynamic cursors.
--By using Ref cursors we can return large amoun
t of data from oracle database into client application.
--There are 2 types of Ref Cursors.
1. Stron
g Ref Cursor.
2. Weak
Ref Cursor.
--Strong Ref Cursor:
--> It i
s one of the ref cursor which has return type.
--Weak Ref Cursor
--> It i

s one of the ref cursor which does not have Return type.
--Normal cursor would keep data in buffer area f
or every Select statement.
--Ref cursor is used because is it saves the buf
fer area. It frees buffer area automatically and hence improves performance.
--In ref cursor we are executing select statemen
ts using open ... for statement.
Eg1:
DECLARE
TYPE T1 IS REF CURSOR;
v_t T1;
I EMP%ROWTYPE;
BEGIN
OPEN v_t FOR SELECT * FROM EMP WHERE SAL>2000;
LOOP
FETCH v_t INTO I;
EXIT WHEN v_t%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||I.ENAME||','|
|I.SAL);
END LOOP;
CLOSE V_T;
END;
Eg2:
SET SERVEROUTPUT ON SIZE 30000;
DECLARE
TYPE T1 IS REF CURSOR;
v_t T1;
I EMP%ROWTYPE;
J DEPT%ROWTYPE;
V_NO NUMBER(5):=&NO;
BEGIN
IF V_NO=1 THEN
OPEN v_t FOR SELECT * FROM EMP;
LOOP
FETCH v_t INTO I;
EXIT WHEN v_t%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||I.ENAME||','|
|I.SAL);
END LOOP;
CLOSE V_T;
ELSIF V_NO=2 THEN
OPEN v_t FOR SELECT * FROM DEPT;
LOOP
FETCH v_t INTO J;
EXIT WHEN v_t%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(J.DEPTNO||','||J.DEPNAME);
END LOOP;
CLOSE V_T;
ELSE
DBMS_OUTPUT.PUT_LINE('INPUT A VALID VALUE 1 OR 2
');
END IF;
END;

--> WHERE CURRENT OF and FOR UPDATE clause:


----------------------------------------> Generally when we are UPDATE, DELETE statements , au
tomatical locks are generated in the database.
--> If we want to generate Locks before Update, Delete s
tatements then we are using cursor locking mechanism in all database systems.
--> In this case we must specify FOR UPDATE clause in cu
rsor defination.
SYNTAX: CURSOR CURSOR_NAME IS SELECT * FROM TABL
E_NAME WHERE CONDITION FOR UPDATE;
--> If we are specifying FOR UPDATE clause Oracle server
does not generate the lock.
ie: Whenever we are opening the cursor then only
oracle server uses internal Exclusive Locks.
--> After processing we must release the lock using COMM
IT statement.
--> WHERE CURRENT OF clause uniquely identifies record i
n each process because WHERE CURRENT OF clause internally uses ROWID.
--> Whenever we are using WHERE CURRENT OF clause we mus
t use FOR UPDATE clause.
Eg1:
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
I EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
IF I.JOB='CLERK' THEN
UPDATE K SET SAL=I.SAL+1000;
//THIS WILL UPDATE FOR ALL RECORDS WITHOUT CHECKING FOR PARTICULAR RECORD.
END IF;
END LOOP;
COMMIT;
END;
DECLARE
CURSOR C1 IS SELECT * FROM EMP;
I EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
IF I.JOB='CLERK' THEN
UPDATE K SET SAL=I.SAL+1000 WHERE EMPID=I.EMPID;
//THIS WILL UPDATE FOR PARTICULAR EMPLOYEE
END IF;
END LOOP;

COMMIT;
END;
//We can achieve above functionality by using where current of feature,
But We must use FOR UPDATE clause in cursor if we are using WHERE CURRENT OF.
DECLARE
CURSOR C1 IS SELECT * FROM EMP FOR UPDATE;
I EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
IF I.JOB='CLERK' THEN
UPDATE K SET SAL=I.SAL+1000 WHERE CURRENT OF C1;
END IF;
END LOOP;
COMMIT;
END;

*************************************************************************
---------EXCEPTIONS
----------->Exception is one of the
errors at runtime.
Types of Exceptions:
1.
2.
3.

activity which is used to handle the


Predefined Exception
User-defined Exception
Un-named Exception

*--> Predefined Exception:


---------------------** It is one of the Exception which are defined
by Oracle.
** There are about 20 Exceptions defined by Orac
le.
Syntax:
when exception1 then
statements;
when exception2 then
statements;
when others then
statements;
Predefined Exceptions are:
1. no_data_found
2. too_many_rows
3. invalid_cursor
4. cursor_already_open

5. invalid_number
6. value_error
7. zero_divide
8. others
etc etc etc
1. NO_DATA_FOUND:
---------------* When a PL/SQL block contains "Select into" cla
use and if requested data not available in the table, Oracle Server returns an e
rror.
* ERROR is ORA-01403:no data found
* To handle this error we are using NO_DATA_FOUN
D exception.
Eg:
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP
WHERE EMPNO=1111;
DBMS_OUTPUT.PUT_LINE(I.E
MPNO||','||I.ENAME);
END;
--Above program will throw no data found exception, we w
ill catch the exception in below program
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP
WHERE EMPNO=1111;
DBMS_OUTPUT.PUT_LINE(I.E
MPNO||','||I.ENAME);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE("Em
ployee Does not exist");
END;
2. TOO_MANY_ROWS:
---------------* When a Select into clause try to return more
than one recor or more than one value then oracle server return error.
* ERROR is ORA-01422:Exact fetch returns more th
an requested number of rows.
* To handle this error we are using TOO_MANY_ROW
S exception.
Eg:
DECLARE
I EMP%ROWTYPE;
BEGIN

SELECT * INTO I FROM EMP


WHERE DEPTNO=40;
DBMS_OUTPUT.PUT_LINE(I.E
MPNO||','||I.ENAME||','||I.DEPTNO);
END;
--Above program will throw TOO_MANY_ROWS exception, we
will catch the exception in below program
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP
WHERE DEPTNO=40;
DBMS_OUTPUT.PUT_LINE(I.E
MPNO||','||I.ENAME||','||I.DEPTNO);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE("WE
CANNOT DISPLAY MORE THAN ONE EMPLOYEE");
END;
--We can also include multiple exception catching code,
Like below example we can have both NO_DATA_FOUND and TOO_MANY_ROWS
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP
WHERE DEPTNO=40;
DBMS_OUTPUT.PUT_LINE(I.E
MPNO||','||I.ENAME||','||I.DEPTNO);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE("Em
ployee Does not exist");
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE("WE
CANNOT DISPLAY MORE THAN ONE EMPLOYEE");
END;

3. INVALID_CURSOR:
-----------------* Whenever we are performing invalid operations
on a cursor, server returns an error.
For eg: If we try to close a cursor without op
ening the cursor then Oracle server returns an error.
* ERROR is ORA-01001: Invalid Cursor
* To handle this error we are using INVALID_CURS
OR exception.
Eg:
DECLARE
CURSOR C1 IS SELECT * FR
OM EMP;
I EMP%ROWTYPE;
BEGIN
--> Note here we have not opened the cursor

LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.E
NAME||','||I.SAL);
END LOOP;
CLOSE C1;
END;
--Above program will throw Invalid Cursor exception, we
will catch the exception in below program
DECLARE
CURSOR C1 IS SELECT * FR
OM EMP;
I EMP%ROWTYPE;
BEGIN
--> Note here we have not opened the cursor
LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.E
NAME||','||I.SAL);
END LOOP;
CLOSE C1;
EXCEPTION
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.PUT_LINE("Op
en The Cursor Properly before closing");
END;

4. CURSOR_ALREADY_OPEN:
----------------------* Whenever we try to RE-OPEN the cursor without
closing the cursor, Oracle server returns an error.
* ERROR is ORA-06511: CURSOR ALREADY OPEN
* To handle this error we are using CURSOR_ALREA
DY_OPEN exception.
Eg:
DECLARE
CURSOR C1 IS SELECT * FR
OM EMP;
I EMP%ROWTYPE;
BEGIN
OPEN C1
--> Note here we have opened the cursor
LOOP
OPEN C1
--> Note here we are again opening an already open cursor
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.E
NAME||','||I.SAL);
END LOOP;
CLOSE C1;
END;

--Above program will throw CURSOR ALREADY OPEN exception


, we will catch the exception in below program
DECLARE
CURSOR C1 IS SELECT * FR
OM EMP;
I EMP%ROWTYPE;
BEGIN
OPEN C1
--> Note here we have opened the cursor
LOOP
OPEN C1
--> Note here we are again opening an already open cursor
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.E
NAME||','||I.SAL);
END LOOP;
CLOSE C1;
EXCEPTION CURSOR_ALREADY
_OPEN THEN
DBMS_OUTPUT.PUT_LINE("Cu
rsor is Open already, Please close before opening again");
END;
5.INVALID_NUMBER:
----------------*Whenever we try to convert string type to numbe
r Oracle server returns error.
*ERROR is ora-01722: invalid number
*To handle this error we are using INVALID_ERROR
Exception.
Eg1:
BEGIN
INSERT INTO EMP(
EMPNO,SAL) VALUES(111,'ABCD');
END;
--Above program will throw invalid number except
ion as we are trying to insert string into NUMBER datatype SAL,
we will catch the exception in below pro
gram
BEGIN
INSERT INTO EMP(
EMP_NO,SAL) VALUES(111,'ABCD')
EXCEPTION
WHEN INVALID_NUMBER
THEN
DBMS_OUTPUT.PUT_
LINE("INSERT PROPER DATA ONLY");
END;
6.VALUE_ERROR:
----------------*Whenever we try to convert string type to numbe
r based on the condition then Oracle server returns error.

*Whenever we try to store large amount of data t


han the specified data type size in variable declaration then Oracle server ret
urns error.
*ERROR is ora-06502: numeric or value error: cha
racter to number conversion error
*To handle this error we are using VALUE_ERROR E
xception.
Eg1:
DECLARE
Z NUMBER(10);
BEGIN
Z:='&X'+'&Y';
DBMS_OUTPUT.PUT_
LINE(Z);
END;
--Above program will throw numeric or value erro
r exception, we will catch the exception in below program
DECLARE
Z NUMBER(10);
BEGIN
Z:='&X'+'&Y';
DBMS_OUTPUT.PUT_
LINE(Z);
EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.PUT_
LINE("ENTER THE PEOPER DATA ONLY");
END;
7.ZERO_DIVIDE:
----------------*Whenever we try to Divide by Zero then Oracle S
erver return a error.
*Error is ORA-01476: divisor is equal to zero
*To handle this error we are using ZERO_DIVIDE E
xception.
Eg1:
DECLARE
A NUMBER(10);
B NUMBER(10):=&B
;
C NUMBER(10):=&C
;
BEGIN
A:=B/C;
DBMS_OUTPUT.PUT_
LINE(A);
END;
--Above program will throw Divide by Zero except
ion, we will catch the exception in below program
DECLARE
A NUMBER(10);
B NUMBER(10):=&B

;
C NUMBER(10):=&C
;
BEGIN
A:=B/C;
DBMS_OUTPUT.PUT_
LINE(A);
EXCEPTION
WHEN ZERO_DIVIDE
THEN
DBMS_OUTPUT.PUT_
LINE('VALUE OF C MUST BE GREATER THAN ZERO)
END;
**-->EXCEPTION PROPAGATION
-->Exceptions are also raised in
1. Exception Sec
tion
2. Executable Se
ction
3. Exception Sec
tion
--> If the Exceptions are raised in Exec
utable section those exceptions are handled using either inner block or an outer
block.
--> Where as If the Exception are raised
in declaration section or in exception section those exceptions are handled usi
ng outer blocks only.
Ex:
BEGIN
DECLARE
Z VARCHA
R2(3):='ABCD';
BEGIN
Z:='ABCD
';
DBMS_OUT
PUT.PUT_LINE(Z);
EXCEPTIO
N
WHEN VAL
UE_ERROR THEN
DBMS_OUT
PUT.PUT_LINE("INVALID STRING LENGTH");
END;
EXCEPTIO
N
WHEN VAL
UE_ERROR THEN
DBMS_OUT
PUT.PUT_LINE("THE LENGTH IS MORE");
END;

*--> User-defined Exception:

-------------------------> We can also create our own e


xception names and also raise whenever it is necessary,
These types of Exception
s are called as User Defined Exception.
-->These Exceptions are divided
into 3 steps.
1. Decla
re Exception
2. Raise
Exception
3. Handl
e Exception
-->DECLARE EXCEP
TION:
--> In Declare section of the PL?SQL program we are defining our own Exception u
sing Exception type.
Syntax:
userdefinedexception_name

exception;

Ex:
DECLARE
A EXCEPTION;
-->Raise Excepti
on:
--> Whenever it is required to raise user defined exception either in executable
section or exception section,
in this case we are using raise keyword.
Syntax:
raise

userdefinedexception_name

Ex:
DECLARE
A EXCEPTION;
BEGIN
RAISE A;
END;

-->Handle Except
ion:
--> We can also handle user defined exceptions same as predefined exception usin
g predefined handler.
Syntax:
when userdefinedexception_name1 then
statements;
when userdefinedexception_name2 then
statements;
------when others then
statements;
EX1:
DECLARE
A EXCEPTION;
BEGIN
IF TO_CHAR(SYSDATE,'DY')='SUN' THEN
RAISE A;
END IF;
EXCEPTION
WHEN A THEN
DBMS_OUTPUT.PUT_LINE("MY EXCEPTION RAISED TODAY");
END;

EX2:
DECLARE
X NUMBER(2):=&X;
Y NUMBER(2):=&Y;
Z NUMBER(2);

A EXCEPTION;
BEGIN
Z:=X+Y;
DBMS_OUTPUT.PUT_LINE(Z);
IF Z>99 THEN
RAISE A;
END IF;
EXCEPTION
WHEN A THEN
DBMS_OUTPUT.PUT_LINE("MY USER DEFINED EXCEPTION RAISED");
END;

--> Raising Pre-defined Exceptio


n:
------------------------------> We can also
raise Predefined Exception using RAISE statement.
SYNTAX:
raise predefinedexceptionname;
EX:
DECLARE
CURSOR C1 IS SELECT * FROM EMP WHERE JOB='CLERK';
I EMP%ROWTYPE;
BEGIN
OPEN C1;
LOOP
FETCH C1 INTO I;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||I.ENAME||','||I.JOB);
IF C1%NOTFOUND THEN
RAISE NO_DATA_FOUND;
END IF;

END LOOP;
CLOSE C1;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE("YOUR JOB NOT AVAILABLE");
END;
--> Exceptions can be called inside another Exception
***IMP***
-->
ERROR Trapping Functions:
------------------------------> There are two error Trapping functions supported by Oracle.
1. SQL Code
2. SQL Errm
1. SQL CODE:
--> It Returns error Numbers
2. SQL Errm:
--> It returns error number with
error message.
Ex:
DECLARE
V_SAL NUMBER(10);
BEGIN
SELECT SAL INTO V_SAL FROM EMP W
HERE EMPNO=7369;
DBMS_OUTPUT.PUT_LINE(SQLCODE);
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
***IMP***
-->
RAISE APPLICATION ERROR:
-----------------------------> If you want to display your own user defined exception numbe
r and exception message then we can use this raise application error.
Syntax:
raise_application_error (error_number,error_mess
age);
Error_Number: Is given between -20000 to -20999
Error_message: Is given message upto 512 charac
ters.
Ex:
DECLARE
A EXCEPTION;
I EMPLOYEES%ROWTYPE;
BEGIN

SELECT * INTO I FROM EMPLOYEES WHERE EMPLOYEE_ID


=100;
IF I.SALARY>2000 THEN
RAISE A;
ELSE
UPDATE EMPLOYEES SET SALARY=SALARY+500 WHERE EMP
LOYEE_ID=I.EMPLOYEE_ID;
END IF;
EXCEPTION
WHEN A THEN
RAISE_APPLICATION_ERROR(-20000,'Salary is alread
y very high');
END;
-->
UN-NAMED EXCEPTION:
----------------------------> If we want to handle other than 20 predefined errors we are
using unnamed method.
--> Because oracle define exception names for regularly occurred
errors other than 20 they are not defining exception names
--> In this case we are providing exception names and also assoc
iate this exception name with appropriate error number using exception_init func
tion.
Syntax: pragma exception_init(userdefined_exception_name
, error_number);
--> Here pragma is a Compiler Directive, i.e at the time of comp
ilation only pl/sql runtime engine associate error number with exception name.
--> This function is used in declare section of the PL/SQL Block
.
EX:
DECLARE
V_NO NUMBER(10);
E EXCEPTION;
PRAGMA EXCEPTION_INIT(E,-2291);
BEGIN
SELECT EMPNO INTO V_NO FROM EMP WHERE EMPNO=&NO;
DBMS_OUTPUT.PUT_LINE(V_NO);
EXCEPTION
WHEN E THEN
DBMS_OUTPUT.PUT_LINE('PRAGMA ERROR');
END;
EX2:
DECLARE
V
EMP%ROWTYPE;
E
EXCEPTION;
PRAGMA EXCEPTION_INIT(E,-2012);
BEGIN
SELECT * INTO V FROM EMP WHERE EMPNO=&ENO;
DBMS_OUTPUT.PUT_LINE(V.EMPNO||','||V.ENAME);
EXCEPTION
WHEN E THEN
DBMS_OUTPUT.PUT_LINE('PRAGMA ERROR');
END;

*************************************************************************
---------SUB PROGRAMS
--------------> Sub Programs are named pl/sql blocks which is used to solve
particular task.
--> There are two types of sub programs supported by Oracle.
1. Procedures
2. Functions
:-->PROCEDURES:
----------------> Procedures may or may not return a value.
--> Procedure return more than one value while using the
out parameter.
--> Procedure can execute in only 3 ways
1. Anonymous block
2. EXEC
3. CALL
--> Procedure can not execute in select statement.
--> Procedure internally has one time compilation proces
s.
--> Procedure are used to improve the performance of bus
iness applications.
--> Every Procedure is having two parts
a) Procedure Specification
-->In procedure
Specification we are specifying name of the procedure and types of the parameter
s.
b) Procedure Body
--> In procedure
body we are solving actual task.
EX:
CREATE OR REPLACE PROCEDURE P1(P_EMPNO NUMBER) I
S
V EMP%ROWTYPE;
BEGIN
SELECT * INTO V FROM EMP WHERE EMPNO=P_EMPNO;
DBMS_OUTPUT.PUT_LINE(V.EMPNO||','||V.ENAME);
END P1;
Ex2:
CREATE OR REPLACE PROCEDURE PROC_NAME(p_EMPLOYEE
_ID NUMBER)
IS
TYPE REC IS RECORD ( P_EMP_ID EMPLOYEES.EMPLOYE
E_ID%TYPE,
P_EMP_NAME EMPLOYEES.FIRST_NAME%TYPE,
P_EMP_START_DATE JOB_HISTORY.START_DATE%TYPE,
P_EMP_END_DATE JOB_HISTORY.END_DATE%TYPE,
P_EMP_JOB_ID JOB_HISTORY.JOB_ID%TYPE,
P_EMP_DEP_NAME DEPARTMENTS.DEPARTMENT_NAME%TYPE);
P_REC REC;
BEGIN
SELECT A.EMPLOYEE_ID,A.FIRST_NAME,B.START_DATE,B
.END_DATE,B.JOB_ID,C.DEPARTMENT_NAME INTO P_REC
FROM EMPLOYEES A,JOB_HISTORY B, DEPARTMENTS C
WHERE A.EMPLOYEE_ID=B.EMPLOYEE_ID

AND A.DEPARTMENT_ID=C.DEPARTMENT_ID
AND A.DEPARTMENT_ID=B.DEPARTMENT_ID
AND A.EMPLOYEE_ID=P_EMPLOYEE_ID;
DBMS_OUTPUT.PUT_LINE(P_REC.P_EMP_ID||','||P_REC.
P_EMP_NAME||','||P_REC.P_EMP_START_DATE||'.'||P_REC.P_EMP_END_DATE||','||P_REC.P
_EMP_JOB_ID||','||P_REC.P_EMP_DEP_NAME);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('We did not find any data f
or given Employee_id: '|| P_REC.P_EMP_ID);
END PROC_NAME;
-------> SHOW ERROR
function can be used to check errors while compiling database objects
--------> All database objects are recorded in ALL_OBJECTS table.
we can check them
DESC ALL_OBJECTS;
-->to check columns in t
hat table
select OBJECT_NAME,OBJECT_TYPE FROM ALL_OBJECTS WHERE OB
JECT_NAME='P1';
--> To find the count of procedures.
select count(1) FROM ALL_OBJECTS WHERE OBJECT_NAME='PROCEDURE';
--> To find who created a Particular Table
select OWNER, OBJECT_NAME from ALL_OBJECTS where OBJECT_NAME='EM
PLOYEE';
--> To find how many database Objects created by each user
select OWNER, count(OBJECT_NAME) from ALL_OBJECTS group by OWNER
;
--> Executing the PROCEDURE:
----------------------------Method 1 :
EXEC P11(7902);
Method 2 : Begin
P11(7902);
end;
Method 3: CALL P11(7902);
Ex2:

Procedure with CURSOR

CREATE OR REPLACE PROCEDURE P111


(P_DEPTNO NUMBER) IS
CURSOR C1 IS SELECT * FROM EMP W
HERE DEPTNO=P_DEPTNO;
I EMP%ROWTYPE;
BEGIN
OPEN C1;

LOOP
FETCH C1 INTO I;
EXIT WHEN C1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(I.ENAME||',
'||I.SAL||','||I.DEPTNO);
END LOOP;
CLOSE C1;
END P111;
--> Parameters in PROCEDURE:
------------------------------> Parameters are used to pass the value into Procedures and al
so return values from the PROCEDURE.
--> In this case we must use two types of parameters:
1. FORMAL PARAMETERS
2. ACTUAL PARAMETERS
--> Formal Parameters:
--> Formal Parameters are defined in Pro
cedure specification.
--> In formal Parameters we are defining
parameter name & mode of the parameter.
--> There are three types of modes suppo
rted by oracle.
1. IN mode
2. OUT mode
3. INOUT mode
1) IN MODE:
--> By Default Procedure paramet
ers is IN mode.
--> IN Mode is used to pass the
values into the Procedure body
--> This mode behaves like a con
stant in Procedure body , through this IN mode we can also pass default values u
sing default or ":=" operator.
EX:
CREATE OR REPLACE PROCEDURE P1(P
_DEPTNO IN NUMBER,
P_DNAME IN VARCHAR2,
P_LOC IN VARCHAR2)
IS
BEGIN
INSERT INTO DEPT VALUES(P_DEPTNO
,P_DNAME,P_LOC);
DBMS_OUTPUT.PUT_LINE("RECORD IS
INSERTED THROUGH PROCEDURE");
END;
--> There are 3 types of EXECUTION METHO
DS supported by IN parameter.
1. Positional Notations
2. Named Notations
3. Mixed Notations
1. Positional Notations:
Ex: EXEC P1(1,'a','b');

2. Named Notations:
Ex: EXEC P1(p_dname=>'x'
,p_loc=>'y',p_deptno=>2);
3. Mixed Notations:
Ex: EXEC p1(1,p_dname=>'
m',p_loc=>'n');

2) OUT MODE:
--> This Mode is used to return
values from procedure body.
--> OUT mode internally behaves
like a uninitialized variable in PROCEDURE body.
Ex1:
create or replace procedure p1(a
IN number, b OUT number) is
begin
b:=a*a;
dbms_output.put_line(b);
end;
NOTE:
In Oracle if a subprogram contains OUT o
r INOUT parameters those subprograms are executed using 2 Methods:
METHOD 1: USING BIND VARIABLE
METHOD 2: USING ANONYMOUS BLOCK
BIND VARIABLE:
--> These variab
les are session variables
--> These variab
les are created at host environment that's why these variables are also called a
s HOST VARIABLES.
--> These variab
les are not a PL/SQL variables, but we can also use these variables in PL/SQL to
execute subprograms having out parameters.
METHOD 1: Bind variable:
Ex:

VARIABLE B NUMBER;
EXEC P1(10,:b);

METHOD 2: Anonymous block


Ex:
DECLARE
C NUMBER(4);
BEGIN
P2(10,20,C);
END;
Program:
1.
Develop a Program for passing employee name as in parameter and
return salary of that employee using out parameter from emp table.

CREATE OR REPLACE PROCEDURE P3(PEMPLOYEE_ID NUMBER, PSALARY OUT


NUMBER)
IS
BEGIN
SELECT SALARY INTO PSALARY FROM EMPLOYEES WHERE EMPLOYEE_ID=PEMP
LOYEE_ID;
DBMS_OUTPUT.PUT_LINE('Salary of the Employee with Emplpoyee_id:
'||PEMPLOYEE_ID||' is : '||PSALARY);
END;
Executing PROCEDURE:
SET SERVEROUTPUT ON;
DECLARE
SAL NUMBER(6);
BEGIN
P3(101,SAL);
END;
or we can also execute using session variable (Bind Vari
able)
VARIABLE V NUMBER;
EXEC P3(101,:V);
2. Develop a Program for Passing deptno as a Parameter return how many emplo
yees are working in that Dept from emp table.

3) INOUT MODE:
--> This Mode is used to pass th
e values into Sub program and return the values from subprogram.
// WE CANNOT EXECUTE ABOVE PROGRAM LIKE
THIS P1(10); AS IT IS AN INOUT VARIABLE.
Ex1:
CREATE OR REPLAC
E PROCEDURE P1(A IN OUT NUMBER) Is
BEGIN
A:=A*A;
DBMS_OUTPUT.PUT_
LINE(A);
END;
METHOD 1: BIND VARIABLE
VARIABLE A NUMBE
R;
EXEC :A:=10;
--Assigning value 10 to variable A.
EXEC P1(:A);
METHOD 2 : ANONYMOUS BLO
CK
DECLARE
A NUMBER(10):=&N

;
BEGIN
P1(A);
DBMS_OUTPUT.PUT_
LINE(A);
END;
EX2:
CREATE OR REPLACE PROCED
URE P4(A IN OUT NUMBER) IS
BEGIN
SELECT SAL INTO A FROM E
MPLOYEE WHERE EMPNO=A;
DBMS_OUTPUT.PUT_LINE(A);
END;

--> PRAGMA Autonomous Transaction in PROCEDURE:


------------------------------------------------Not Explained

:-->FUNCTIONS:
----------------> Function is a named PL/SQL block which is used to So
lve Particular task and by default functions return a single Value.
--> Function allows to return Multiple Return Statements
but it Execute only First return statement
--> Function can execute in 4 ways:
1. Anonymous Block
2. Select Statement
3. Bind Variable
4. EXEC
--> Like PROCEDURE Function is also having 2 Parts.
1. Function Specification
2. Function Body
--> In function specification we are specifying name of
the function and type of the parameters where as in function body we are solving
the actual task.
Ex:
CREATE OR REPLACE FUNCTION F1( A VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
RETURN A;

END;
EXECUTING Function:
1. ANONYMOUS Block:
DECLARE
A VARCHA
R2(10):='WELCOME';
BEGIN
A:=F1('W
elcome');
DBMS_OUT
PUT.PUT_LINE(A);
END;
2. BIND Variable:
VARIABLE A Varch
ar2(10);
Begin
:A:=F1('WELCOME'
);
END;
3. EXEC:
EXEC DBMS_OUTPUT.PUT_LIN
E(F1('Welcome'));
4. SELECT:
SELECT F1('WELCOME TO AP
PS') FROM DUAL;

Ex2: Identifying a Number even or ODD.


CREATE OR REPLACE Function FUN2(A NUMBER)
RETURN VARCHAR2
IS
Begin
IF MOD(A,2)=0 THEN
RETURN 'EVEN NUMBER';
ELSE
RETURN 'ODD NUMBER';
END IF;
END;
EX3: Addition of two Numbers
CREATE OR REPLACE FUNCTION FUN3(A NUMBER,B NUMBER)
RETURN NUMBER
IS
BEGIN
RETURN a+b;
END;
NOTE: If we want to return more number of values from Function we are us
ing OUT parameter.
Ex:

CREATE OR REPLACE FUNCTION FUN4(P_DEPTNO IN NUMBER,


P_DNAME OUT VARCHAR2,
P_LOC OUT VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
SELECT DNAME,LOC INTO P_DNAME,P_LOC FROM DEPT WHERE DEPTNO=P_DEP
TNO;
RETUN P_DNAME;
END;
Executing Functions with IN, OUT , INOUT paramters:
variable a varchar2(10);
variable b varchar2(10);
variable c varchar2(10);
begin
:A=fun4(10,:b,:C);
end;
print b;
print c;
PROGRAM:
1. Write a PL/SQL stored function for passing empno as parameter
return gross salary from emp table based on following condition?
Condition==> gross:=basic+hra+da+pf;
hra=> 10% of Salary
da => 20% of Salary
pf => 10% of salary
2. Write a PL/SQL stored function for passing empno,date as para
meter return number of years that employee is working based on date from emp tab
le.
3. Write a PL/SQL stored function for passing empno
, calculate tax based on following conditions by using emp table.
Condition:
1. If Annual Salary
tax=10%
2. If Annual Salary
tax=20%
3. If Annual Salary
tax=30%

as parameter
> 10000 then
> 20000 then
> 50000 then

*************************************************************************
--------PACKAGES
----------> Package is a Database Object which is used to encapsulate variables,
constants, procedures, cursors, functions, types in to Single Unit.
--> Package does not accept Parameters, cannot be nested , cannot be Inv
oked.
--> Generally Packages are used to Improve performance of the Applicatio
n
because when we are calling packaged subprogram first time total
package is automatically loaded into memory area.
--> Whenever we are calling Subsequent sub program calls pl/sql run time

engine calling those sub program from memory area.


--> This Process automatically reduces disk I/O that's why package impro
ves performance of the application
--> Packages have two Sections:
1. Package Speci
fication
2. Package Body
--> In package Specification we are defining global data
and also declare objects, sub programs
where as in Package body we are implementing sub
programs and also package body sub program internally behaves like a private su
b program.
Package Specification Syntax:
CREATE OR REPLACE PACKAGE PACKAGE_NAME
IS/AS
GLOBAL VERIABLE DECLARATION;
CONSTANT DECLARATION;
CURSOR DECLARATION;
TYPES DECLARATION;
PROCEDURE DECLARATION;
FUNCTION DECLARATION;
END;
Package Body Syntax:
CREATE OR REPLACE PACKAGE BODY
PACKAGE_NAME
IS/AS
PROCEDURE IMPLEMENTATION;
FUNCTION IMPLEMENTATION;
END;
Invoking Packaged Subprograms:
1. EXEC Package_Name.Procedure_Name(Actual PARAMETERS);
2. Select Package_Name.Function_Name(Actual PARAMETERS) from DUAL;

EX1:
CREATE OR REPLACE PACKAGE P1
IS

PROCEDURE P1;
PROCEDURE P2;
END;
CREATE OR REPLACE PACKAGE BODY PACK1
IS
PROCEDURE P1
BEGIN
DBMS_OUTPUT.PUT_LINE("PROCEDURE P1");
END P1;
PROCEDURE P2
BEGIN
DBMS_OUTPUT.PUT_LINE("PROCEDURE P2")
END P2;
END PACK1;
--> We can execute only one object from a Package at a time.
--> To execute one object from Package we have to execute in the
way mentioned below.
EXEC PACK1.P1;
(PACKAGE NAME.PROCEDURE NAME)
EX2:
CREATE OR REPLACE PACKAGE PACK1
IS
PROCEDURE P1(A NUMBER, B NUMBER, C OUT NUMBER);
PROCEDURE P2(X NUMBER, Y NUMBER);
END;
CREATE OR REPLACE PACKAGE BODY PACK1
IS
PROCEDURE P1(A NUMBER, B NUMBER, C OUT NUMBER)
IS
BEGIN
C:=A+B;
END P1;
PROCEDURE P2(X NUMBER, Y NUMBER)
IS
Z NUMBER(5);
BEGIN
Z:=X-Y;
DBMS_OUTPUT.PUT_LINE(Z);
END P2;
END PACK1;
SET SERVEROUTPUT ON;
DECLARE
C NUMBER(5);
BEGIN
PACK1.P1(10,20,C);
DBMS_OUTPUT.PUT_LINE(C);
END;
SET SERVEROUTPUT ON;

exec PACK1.P2(20,10);

--> Global Variables & Local Variables:


--------------------------------------GLOBAL VARIABLE:
--> It is one of the variable which is used to d
efine in package Specification and implement in Package body that variables are
called as Global Variable.
LOCAL VARIABLE:
--> It is one of the variable which is used to d
efine in programs (Procedures, Function) and implement with in the program only.
Package Specification:
Eg:
Create or replace package pack1 is
g number(5):=500;
procedure p1;
function f1(a number) return number;
end;
Package Body:
Ex:
create or replace package body pack1 is
procedure p1
is
z number(5);
z:=g/2;
// g is Global variable
dbms_output.put_line(z);
// z is local variable of procedure p1
end p1;
function f1(a number ) return number
is
begin
return a*g;
end f1;
end;
--> PROCEDURE OVERLOADING:
---------------------------> Overloading refers to same name can be used
for different purpose.
-->We are implementing overloading procedures th
rough packages only.
-->Those Procedures which have same name but dif
ferent types of Arguments are called as function Overloading.
EX:
CREATE OR REPLACE PACKAGE PACK4
IS
PROCEDURE P1(A NUMBER, B NUMBER)
;
PROCEDURE P2(X NUMBER, Y NUMBER)
;
END;

CREATE OR REPLACE PACKAGE BODY P


ACK4
IS
PROCEDURE P1(A NUMBER, B NUMBER)
IS
C NUMBER(5);
BEGIN
C:=A+B;
DBMS_OUTPUT.PUT_LINE(C);
END P1;
PROCEDURE P1(X NUMBER, Y NUMBER)
IS
Z NUMBER(5);
BEGIN
Z:=X*Y;
DBMS_OUTPUT.PUT_LINE(Z);
END P1;
END PACK4;
EXECUTING:
EXEC PACK4.P1(A=>10,B=>20);
O/P=30
EXEC PACK4.P1(X=>10,Y=>20);
O/P=200
-->Forward Declaration:
-------------------------> Whenever we are calling procedures into anot
her procedure then only we are using forward declaration.
--> That means, when we are calling local proced
ures into global procedure first we must implement local procedures before calli
ng otherwise use a forward declaration in package body.
CREATE OR REPLACE PACKAG
E PACK5 IS
PROCEDURE P1;
END;
CREATE OR REPLACE PACKAG
E BODY PACK5 IS
PROCEDURE P2;
//This is Local PROCEDURE called inside global procedure so declaring before the
call & implementation.
PROCEDURE P1;
IS
BEGIN
P2;
//Local proc called
END P1;
PROCEDURE P2
//Implementing local proc
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('lO
CAL procedure');
END P2;
END;

*************************************************************************
-------TRIGGERS
---------> Triggers are also same as Stored Procedures, Triggers are au
tomatically invoked whenever DML operations are performed against table or a vie
w.
--> There are Two Types of Triggers Supported by PL/SQL
1. Statement Level Trigger:
** In Statement Level Trigger , Trigger
Body is executed only once for DML statements.
2. Row Level Trigger
** In Row Level Trigger, Trigger body is
executed for each and every DML statements.
Syntax:
CREATE {OR REPLACE} TRIGGER TRIGGER_NAME
BEFORE/AFTER TRIGGER_EVENT
INSERT or UPDATE or DELETE ON TABLE_NAME
{for each row}
{where condition}
{DECLARE}
variable declarations, cursors
BEGIN
-----END
EXECUTION ORDER IN
1.
2.
3.
4.

TRIGGER:
Before Statement Level
Before Row Level
After Row Level
After Statement Level

1. Statement Level Trigger:


-----------------------------> In Statement Level Trigger. Trigger body is
executed only once for each DML statement.
--> Thats why generally statement level triggers
used to define type based condition and also used to implement auditing reports
.
--> These triggers does not contain new, old qua
lifiers.
Q: Write a PL/SQL statement Level Trigge
r on EMPLOYEE table not to perform DML operations in saturday and sunday ?
CREATE OR REPLACE TRIGGE
R TR1 BEFORE INSERT OR UPDATE OR DELETE ON EMPLOYEE
BEGIN
IF TO_CHAR(SYSDATE,'DY')
IN ('SAT','SUN')
THEN
RAISE_APPLICATION_ERROR(
-20123, 'WE CANNOT PERFORM DML OPERATIONS ON SAT AND SUN');
END IF;
END;

Q: Write a PL/SQL statement Level Trigge


r on EMPLOYEE table not to perform DML operations on Last day of Month?
CREATE OR REPLACE TRIGGE
R TR2 BEFORE INSERT OR UPDATE OR DELETE ON EMPLOYEE
BEGIN
IF SYSDATE=LAST_DATE(SYS
DATE)
THEN
RAISE_APPLICATION_ERROR(
-20111, 'WE CANNOT PERFORM DML OPERATIONS ON END OF THE MONTH.');
END IF;
END;
--> Trigger Event (OR) Trigger Predicate Clauses
:
---------------------------------------------> If you want to defin
e Multiple conditions on Multiple tables then all database systems uses trigger
events.
--> These ate Inserting
, Updating , deleting clauses.
--> These clauses are us
ed in either row level or statement level triggers.
Syntax:
if inserting then
statements;
elseif updating then
statements;
elseif deleting then
statements;
end if;
Q: Write a PL/SQL Statement Level Trigge
r on EMPLOYEE table not to perform any DML Operations in Any days using trigger
event?
CREATE OR REPLACE TRIGGE
R TR3 BEFORE UPDATE OR INSERT OR DELETE ON EMPLOYEE
IS
IF INSERTING THEN
RAISE_APPLICATION_ERROR(
-20000,'YOU ARE NOT SUPPOSED TO INSERT INTO THIS TABLE');
ELSIF UPDATING THEN
RAISE_APPLICATION_ERROR(
-20001,'YOU ARE NOT SUPPOSED TO UPDATE THIS TABLE');
ELSIF DELETING THEN
RAISE_APPLICATION_ERROR(

-20002,'YOU ARE NOT SUPPOSED TO DELETRE FROM THIS TABLE');


END IF;
Example for AFTER TRIGGER:
------------------------CREATE TABLE TEST(MSG VA
RCHAR2(100));
CREATE OR REPLACE TRIGGE
R TR4 AFTER INSERT OR UPDATE OR DELETE ON TT
DECLARE
A VARCHAR2(50);
BEGIN
IF INSERTING THEN
A:='ROWS INSERTED';
ELSIF UPDATING THEN
A:='ROWS UPDATED';
ELSIF DELETING THEN
A:='ROW DELETED';
END IF;
INSERT INTO TEST VALUES
(A);
END;

2. Row Level Trigger:


----------------------> In Row Level Trigger, Trigger Body is execut
ed for each row of DML Statement.
-->That's why we are using for each row Clause i
n Trigger Specification.
-->Also data internally is stored in 2 Rollback
segment qualifiers OLD & NEW
-->These Qualifers are used in either Trigger sp
ecification or in Trigger Body.
-->when we are using these Modifiers in Trigger
Body We must use Colon Prefix in the Qualifers.
Syntax:
--> :old.column_name

(or) :n

ew.column_name
-->When We are Using These Qualifiers in when cl
ause we are not allowed to use colon in front of the Qualifers.
BEFORE VS AFTER TRIGGER:-----------------------> In Before Trigger , Trigger body is
executed before DML statements are effected into database.
--> In After Triggers, Trigger body is e
xecuted after DML statements are effected into database.
--> Generally if we want to restrict inv
alid data entry always we are using before triggers,
where as if we are performing op
eration on the one table those operations are effected in another table then we
are using after Trigger.
--> Whenever we are Inserting values int

o new Qualifiers we must use before Trigger otherwise Oracle Server returns an e
rror.
Q: Write a PL/SQL Row Level Trigger on EMP Table whenever user inserting
data into a emp table salary should be more than 5000.
-->
CREATE OR REPLACE TRIGGER T90 BEFORE INS
ERT ON EMP
FOR EACH ROW
BEGIN
IF :NEW.SAL<5000 THEN
RAISE_APPLICATION_ERROR(-20123,'SALARY S
HOULD BE MORE THAN 5000');
END IF;
END;
ON DELETE CASCADE:
------------------While deleting a record, if there is dependency of that record in any other tabl
e.
Those records also will be deleted if ON DELETE CASCASE is set ON.
Q: Write a PL/SQL Row Level Trigger on EMP, DEPT Tables for implementing
on delete cascade concept, without using On DELETE cascade Clause.
CREATE OR REPLACE TRIGGER T91
AFTER DELETE ON DEPT
FOR EACH ROW
BEGIN
DELETE FROM EMP WHERE DEPTNO=:OLD.DEPTNO
;
END;
Q: Write a PL/SQL Row Level Trigger on DEPT table whenever updating dept
no's in DEPT table automatically those deptno's modified into emp table.
CREATE OR REPLACE TRIGGER T19
AFTER UPDATE ON DEPT
FOR EACH ROW
BEGIN
UPDATE EMP SET DEPTNO=:NEW.DEPTNO WHERE
DEPTNO=:OLD.DEPTNO;
END;
Q: Write a PL/SQL Row Level Trigger Whenever user inserting data into en
ame column after inserting data must be converted into uppercase.
CREATE OR REPLACE TRIGGER T20
BEFORE INSERT ON EMPLOYEE
FOR EACH ROW
BEGIN
:NEW.ENAME=UPPER(:NEW.ENAME);
END;
Q: Write a PL/SQL Row Level Trigger on EMP table by using below Conditio
n?
1. Whenever user Inserting data those values stored in a

nother table.
2. Whenever user Updating data those values stored in an
other table.
3. Whenever user Deleting data those values stored in an
other table?
create table employee as EMP;

//1st create one

similar table
create or replace trigger t1 after insert or delete or u
pdate on emp
for each row
begin
if inserting then
insert into employee(empno,ename) values(:new.empno,:new
.ename);
elseif updating then
insert into employee(empno,ename) values(:old.empno,:old
.ename);
elseif deleting then
insert into employee(empno,ename) values(:old.empno,:old
.ename);
end if;
end;
Q: Write a PL/SQL Row Level Trigger on EMP table, whenever a record is d
eleted display the number of records available in the Table after the delete.
CREATE OR REPLACE TRIGGER T1 AFTER DELETE ON EMP
FOR EACH ROW
DECLARE
CNT INT;
BEGIN
SELECT COUNT(*) INTO CNT FROM EMP;
DBMS_OUTPUT.PUT_LINE("No of records now availabl
e in EMP table : "||CNT);
END;

MUTATING TRIGGER:
-----------------

*************************************************************************
VVIP
-----------COLLECTIONS
-----------1. PL/SQL Record (or) Record Type
2. Index by Table (or) PL/SQL table (or) Associative Arrays
3. Nested Tables

4. Varrays
5. Ref Cursors

-->Record Type ( or ) Pl/Sql Record


------------------------------>Is is one of the user defined temporary data type which is used to store more
than one table data ( or ) to assign more than one column datatypes.
-->They must at least contain one element.
-->Pinpoint of data is not possible.
Syntax : Type Typename is Record ( Val-1 Datatype, Val-2 Datatype, ..);
Var Typename
Ex :
Declare
Type Rec is record ( vname emp.ename%type,
Vsal emp.sal%type,
VLoc dept.loc%type);
Vrec Rec;
Vno emp.empno%type:=&n;
Begin
Select ename,sal,loc into vrec from emp,dept where emp.deptno=dept.deptno and em
p.empno=vno;
Dbms_output.put_line(vrec.vname|| , ||vrec.vsal|| , ||vrec.vloc);
End;
-->INDEX BY TABLE:
---------------> This is an User defined type which i
s used to store Multiple data items to a Single Unit. Basically this is an Non-c
onstraint table.
--> Generally these tables are used to i
mprove performance of applications because these tables are stored in Memory are
a thats why These tables are also called as Memory Tables.
--> Basically These Table Contains Key V
alue Pairs, i.e Value field is Stored in Actual Data and Key field Stored in Ind
exes.
--> Key Field Values are either Integer
or Character and also these values are either +ve or -ve.
--> These Indexes key behaves like prima
ry key, i.e does not accept duplicate and null values, basically this key dataty
pe is binary_integer.
--> Index by Table Having following COLL
ECTIONS Mrthods.
1. EXIST
S
2. FIRST
3. LAST
4. PRIOR
5. NEXT
6. COUNT
7. DELET
E(range of indexes)

SYNTAX:
TYPE type_name IS TABLE
(binary_integer,

of datatype(size) index by index_type;


vrachar2, date etc can be index_type)

variable_name type_name;
////INDEX OF TABLE for NUMBER.
Eg1:
DECLARE
TYPE T1 IS TABLE
OF NUMBER(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
V_T(1):=10;
V_T(2):=20;
V_T(3):=30;
V_T(4):=40;
V_T(5):=50;
DBMS_OUTPUT.PUT_
LINE(V_T(3));
DBMS_OUTPUT.PUT_
LINE(V_T.first);
DBMS_OUTPUT.PUT_
LINE(V_T.last);
DBMS_OUTPUT.PUT_
LINE(V_T.prior(3));
DBMS_OUTPUT.PUT_
LINE(V_T.next(4));
DBMS_OUTPUT.PUT_
LINE(V_T.count);
DBMS_OUTPUT.PUT_
LINE(V_T(5));
END;
Eg2:
DECLARE
TYPE T1 IS TABLE
OF NUMBER(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
V_T(1):=10;
V_T(2):=20;
V_T(3):=30;
V_T(4):=40;
V_T(5):=50;
DBMS_OUTPUT.PUT_
LINE(V_T.count);
V_T.DELETE(2,3);
//Will Delete 2nd to 3rd Record.
DBMS_OUTPUT.PUT_
LINE(V_T.count);
V_T.DELETE;
//Will Delete all records, if index is not specified.
DBMS_OUTPUT.PUT_
LINE(V_T.count);
V_T.DELETE(1);
//Will Delete 1st record
DBMS_OUTPUT.PUT_

LINE(V_T.count);
V_T.DELETE(1,3);
//Will Delete 1st to third record
END;
//INDEX OF TABLE for VARCHAR.
WRITE A PL/SQL PROGRAM TO GET ALL EMPLOY
EE NAMES FROM EMP TABLE AND STORE IT INTO INDEX BY TABLE AND DISPLAY DATA FROM I
NDEX BY TABLE?
SOLUTION:
DECLARE
TYPE T1 IS TABLE OF VARC
HAR2(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
FOR I IN 1..10
LOOP
FETCH C1 INTO V_T(N);
EXIT WHEN C1%NOTFOUND;
N:=N+1;
END LOOP;
CLOSE C1;
FOR I IN V_T.FIRST..V_T.
LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(1));
END LOOP;
END;
//Above same Programm can be Implemented Using FOR LOOP.
.!! We Use FOR LOOP because in FOR LOOP, we dont have to Open Cursor, close Curs
or or Initialise variable.
DECLARE
TYPE T1 IS TABLE OF VARC
HAR2(10) INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
SELECT ENAME BULK COLLEC
T INTO V1 FROM EMP;
FOR I IN V1.FIRST..V1.LA
ST
LOOP
DBMS_OUTPUT.PUT_LINE(V1(
I));
END LOOP;
END;
//INDEX OF TABLE for DATE.
DECLARE
TYPE T1 IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
FOR I IN 1..10

LOOP
V_T(I):=SYSDATE+i;
END LOOP;
FOR I IN V_T.FIRST..V_T.
LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(I));
END LOOP;
END;

DECLARE
TYPE T1 IS TABLE OF DATE
INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
SELECT HIREDATE BULK COL
LECT INTO V1 FROM EMP;
FOR I IN V_T.FIRST..V_T.
LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(I));
END LOOP;
END;
//INDEX BY VARCHAR2
DECLARE
TYPE T1 IS TABLE OF VARC
HAR2(10)
INDEX BY VARCHAR2(10);
V_T T1;
X VARCHAR2(10);
BEGIN
V_T('A') = 'ARUN';
V_T('B') = 'AJAY';
V_T('C') = 'ABHI';
X:='A'
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
('X'));
X:=V_T.NEXT(X);
EXIT WHEN X IS NULL;
END LOOP;
END;
Eg of rowtype in index by table:
DECLARE
TYPE T1 IS TABLE OF emp%
rowtype
INDEX BY binary_integer;
V_T T1;
X NUMBER(5);
BEGIN

SELECT * BULK COLLECT IN


TO V_T FROM EMP;
X:=1;
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(X).empno || ',' || V_T(X).ename);
X:=V_T.NEXT(X);
EXIT WHEN X IS NULL;
END LOOP;
END;

DECLARE
TYPE T1 IS TABLE OF emp%
rowtype
INDEX BY binary_integer;
V_T T1;
BEGIN
SELECT * BULK COLLECT IN
TO V_T FROM EMP;
FOR I IN V_T.FIRST..V_T.
.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V_T
(I).empno || ',' || V_T(I).ename);
END LOOP;
END;

-->NESTED TABLES:
--------------->
This is user defined type which
is used to store multiple data items in single unit
but before storing actual data w
e have to initialise the data while using Constructor
-->
Here constructor name is same as
Type name.
-->
Generally we are not allowed to
store Index By Table permanently in Database, to overcome this problem
they intodcued NESTED TABLES.
-->
These user defined types are per
manently stored in database.
-->
In Index by table we cannot add
or remove indexes, where as in NESTED TABLES we can add or remove indexes by usi
ng EXTEND, TRIM Collection methods.
-->
In NESTED TABLES we can allocate
memory explicitly while using EXTEND method.
SYNTAX:
TYPE type_name IS TABLE
of datatype(size);
:= TYPE_NAME();
-->VARRAYS:

variable_name type_name
--> Constructor

--------------->
This is user defined type which
is used to store multiple data items in single unit
but before storing actual data w
e have to initialise the data while using Constructor
-->
Here constructor name is same as
Type name.
-->
These user defined types are per
manently stored in database.
-->
Basically we are using the VARRA
YS for retrieveing HUGE DATA.
SYNTAX:
TYPE type_name IS VARRAY
(maxsize) of datatype(size);
variable_name type_name
:= TYPE_NAME();

Difference between INDEX BY TABLE, NESTED TABLES and VAR


RAYS
INDEX BY TABLE
NESTED TABLES
VARRAYS
1. Not permanently stored in Database
Permanently stored in Database
Permanently stored in Database
2. Index cannot be added or removed
Index can be added or removed using
Extend or trim
n be added or removed using
Extend or trim
`
3. Index starting from negative to
Indexes start from 1
Indexes start from 1
positive numbers and also having
key value Pairs

Index ca

*************************************************************************
-->BULK MECHANISM:
---------------> Bulk is one of the method which is used to improve t
he performance of the applications.
--> Oracle introduced bulk bind processing collection i.
e in this process all sql statement related values into collections
and in this collection we are performing DML ope
ration like INSERT, UPDATE , DELETE using FOR ALL statement.
--> In this Bulk we have two options
1. BULK COLLECT
2. BULK BIND

--> BULK COLLECT:


-------------> In this mechanism we
fetch the data from Resource into Collection.
--> This clauses used in
1. Select into clauses
2. Cursor Fetch clauses
3. DML returning clauses
--> Select into
clauses
----------------------SYNTAX:
SELECT * BULK COLLECT INTO COLLECTION_NAME FROM TABLE_NAME;

EG:
DECLARE
TYPE T1 IS TABLE OF EMP%ROWTYPE INDEX BY BINARY INTEGER;
V T1;
BEGIN
SELECT * BULK COLLECT INTO V FROM EMP;
FOR I IN V.FIRST..V.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V(I).EMPNO||','|| V(I).ENAME||','||V(I).JOB);
END LOOP;
END;
--> Cursor Fetch
clauses
-----------------------SYNTAX:
FETCH CURSOR_NAME BULK COLLECT INTO COLLECTION_NAME;
Eg1:

SET SERVEROUTPUT ON
DECLARE
TYPE T1 IS TABLE OF EMP%ROWTYPE
INDEX BY BINARY_INTEGER;
V1 T1;
CURSOR C1 IS SELECT * FROM EMP;
BEGIN
OPEN C1;
FETCH C1 BULK COLLECT INTO V1;
CLOSE C!;
FOR i IN
V1.FIRST..V1.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V1(i).EMPNO||','||v1(i).ename||','||v1(i).job);
END LOOP
;
END;
Eg: TIME PROGRAM WITHOUT BULK FUNCTION.
declare
var1 varchar2(500) NULL;
n1 number(30);
n2 number(30);
ti number(30);
cursor c1 is select object_name from all_objects;
begin
n1:=DBMS_UTILITY.get_time();
open c1;
loop
fetch c1 into var1;
exit when c1%notfound;
end loop;
close c1;

n2:=DBMS_UTILITY.get_time();
dbms_output.put_line('Start Time: ' || n1);
dbms_output.put_line('End Time: ' || n2);
ti:=n2-n1;
dbms_output.put_line('Total Time Taken: ' || ti);
end;
OUTPUT:
Start Time: 2808071
End Time: 2808138
Total Time Taken: 67

Eg: TIME PROGRAM WITH BULK FUNCTION.


declare
var1 varchar2(500) NULL;
n1 number(30);
n2 number(30);
ti number(30);
cursor c1 is select object_name from all_objects;
begin
n1:=DBMS_UTILITY.get_time();
open c1;
loop
fetch c1 into var1;
exit when c1%notfound;
end loop;
close c1;
n2:=DBMS_UTILITY.get_time();
dbms_output.put_line('Start Time: ' || n1);
dbms_output.put_line('End Time: ' || n2);
ti:=n2-n1;
dbms_output.put_line('Total Time Taken: ' || ti);

end;
OUTPUT:
Start Time: 3824472
End Time: 3824514
Total Time Taken: 42
-->BULK
COLLECT used in DML Returning clauses.
----------------------------------------SYNTAX:
DML statement returning coloumn_name into variable_name;

Eg1:
VARIABLE A VARCHAR2(10);
UPDATE EMP SET SAL=SAL+1000 WHERE EMP_NAME='KING' RETURNING COLUMN_NAME BULK COL
LECT INTO :A;
PRINT A;
Eg2:
Write a
PLSQL Procedure to update salaries of clerk in Employee Table and also these upd
ates salries are
immediat
ely stored into INDEX BY TABLE by using DML Returning clause, and also display c
ontents from INDEX BY TABLE.
set serveroutput
on;
DECLARE
TYPE T1 IS TABLE
OF EMP%ROWTYPE INDEX BY BINARY_INTEGER;
V1 T1;
BEGIN
UPDATE EMP SET S
AL=SAL-1000 WHERE JOB='clerk' RETURNING EMPNO,ENAME,SAL, JOB,DEPTNO BULK COLLECT
INTO V1;
dbms_output.put_
line('Updated number of Clerks are :'|| sql%rowcount );
for i in v1.firs
t..v1.last
loop
dbms_output.put_
line(v1(i).EMPNO||','||v1(i).ENAME||','||v1(i).sal||','||v1(i).job||','||v1(i).d
eptno );
end loop;
END;

--> BULK BIND:


-----------> In BULK BIND process
we are performing bulk operations using collections.
ie. In thsi proc
ess we are using BULK UPDATE, BULK DELETE, BULK INSERT using FORALL Statement.
--> Before using BULK BI
ND process we are fetching data from database into collections using BULK COLLEC
T clause.
SYNTAX:
forall indexvar in collectionvar.first..collectionvar.last
Eg1 BULK UPDATE:
---------------SET SERV
EROUTPUT ON
DECLARE
TYPE T1
IS TABLE OF EMP.EMPNO%TYPE INDEX BY BINARY_INTEGER;
V1 T1;
BEGIN
SELECT E
MPNO BULK COLLECT INTO V1 FROM EMP;
FORALL I
IN V1.FIRST..V1.LAST
UPDATE E
MP SET SAL=SAL+1000 WHERE EMPNO=V1(I);
END;
Eg2 BULK DELETE:
---------------SET SERV
EROUTPUT ON
DECLARE
TYPE T1
IS TABLE OF EMP.EMPNO%TYPE INDEX BY BINARY_INTEGER;
V1 T1;
BEGIN
SELECT E
MPNO BULK COLLECT INTO V1 FROM EMP where job='President';
FORALL I
IN V1.FIRST..V1.LAST
delete f
rom emp WHERE EMPNO=V1(I);
END;
Eg3 BULK INSERT:
---------------SET SERV
EROUTPUT ON
DECLARE
TYPE T1
IS TABLE OF EMP.EMPNO%TYPE INDEX BY BINARY_INTEGER;

V1 T1;
BEGIN
for i in
1..100
loop
v1(i):=i
;
end loop
;
FORALL I
IN V1.FIRST..V1.LAST
insert i
nto bt
values(v
1(i));
END;
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------SQL
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------SQL->
? Introduction to SQL
Level 1 - Data Types
1. Number:
-->It allows only numeric values
--> Maximum Size is 38 digits
Syntax: X Number(P,(S));
P--> It allows how many digits to store.
S--> Size
Eg:
X Number(5,2);
2. Char
--> It allows alphanumeric characters (N
umbers + Characters)
--> Maximum size is 2000 bytes /characte
rs
Syntax: X Char(S);
S--> Size
3. Varchar

or VARCHAR2
--> It allows Alphanumeric characters
--> Max size 4000 bytes /characters
--> Memory Allocation is dynamic
Syntax: X VARCHAR2(50);

4. Date
--> It is used to store date values
--> Max size is 7 bytes
Syntax: X date;
5. Timestamp
--> It is used to store date along with
fraction of seconds.
Syntax: X Timestamp;
6. Long
--> It is used to store information
--> Max Size 2GB
--> Only once we have to use in Entire t
able
Syntax: X Long;
7. Raw
--> It is used to store images
--> Max size is 2000 Bytes
Syntax: X Raw;
8. LongRaw
--> It is used to store information as w
ell as images
--> Max size is 2GB
Syntax: X Longraw;
9. Lob ( CLob, Blob,BFile & NCLob )
1. CLOB:
--> It is used to store huge inf
ormation
--> Max size is 4GB
Syntax: X Clob;
2. BLOB:
--> It is used to store images b
ut in the binary format
--> Max size is 4GB
Syntax: X Blob;
3. BFILE:
--> It is used to store the file
s
--> Max size is 4GB
Syntax: X Bfile;
4. NCLOB:
--> It is used to store Multiple
Languages (Unicode format)
Level 2 - SQL Statements

? DDL
*Create
*Alter
*Drop
? DML
*Insert
*Update
*Delete
? DQL
*Select
? TCL

--> It is used to save transactions on a table.


*Commit --> It is executed to save the changes permanent

ly on the database.
1. IMPLICIT COMMIT: Automaticall
y executed by the system.
2. EXPLICIT COMMIT: Manually exe
cuted by user.
*Rollback--> It is executed to revert back the last chan
ges.
*Savepoint--> It is used to mark a specific ecord, It is
only for temporary purpose.
Eg: SAVEPOINT S1;
*Truncate--> It works like Delete + Commit, Syntax: TRUN
CATE TABLE Table_name;
? DCL
Level 3 - Clauses
?
?
?
?
?
?
?

--> It is used to provide access to users.

Select
From
Where
Group By
Having
Order By
DISTINCT

Level 4 - Operators
? Arthemetic Operators
1. /
2. *
3. +
4. ? Logical Operators
1. And
2. Or
3. Not
? Relational Operators
1. =
2. <
3. >
4. <=
5. =>
6. !=
? Special Operators
1. Is
2. In
3. Not In
4. Between
5. Like
? Set Operators

1.
2.
3.
4.

Union
Union All
Intersect
Minus

Level 5 - Functions
? Number Functions
1. Power
2. Sqrt
3. Mod
4. Ascii
5. Ceil
6. Floor
7. Round
8. Trunc
? String Functions
1. Length
2. Reverse
3. Concat
4. Ltrim
5. Rtrim
6. Trim
7. Lpad
8. Rpad
9. Translate
10.Replace
11.Decode
? Date Functions
1. Sysdate
2. Current_Date
3. Add_Months
4. Months_Between
5. Next_Day
6. Last_Day
? Conversion Functions
1. To_Char
2. To_Date
3. To_Number
? General Functions
1. Greatest
2. Least
3. Nvl
4. Nvl2
5. Case
? Aggrigate Functions
1. Count (*)
2. Count ( Column )
3. Min
4. Max
5. Avg
6. Sum
Level 6 - Constraints
? Primary Key
? Composite Primary Key
? Unique
? Not Null
? Check
? Foreign Key
Level 7 - Joins
? Simple Join

? Equi Join
? Non Equi Join
? Outer Join
? Left Outer Join
? Right Outer Join
? Full Outer Join
? Self Join
Level 8 - Synonyms
--> It is used to hide the owner
of the table.
--> It works like a mirror image
of the table.
--> It does not have its own str
ucture.
--> It is dependent on the table
.
--> We can create synonym on tab
le, we never create synonym directly.
--> All synonyms are stored in U
SER_SYNONYMS table.
--> Synonysm fetch data from Tab
le, we can insert, update , delete on Synonym which will internally do same oper
ation on table.
--> Synonym can be created on an
other synonym,however source will be table.
? Public Synonym
--> It is used to create Public
Synonym in current schema but can be accessed through other schemas as well.
Syntax:
CREATE P
UBLIC SYNONYM synonym_name for table_name;
? Private Synonym
--> It is used to create Private
Synonym in current schema and can be accessed on through that schema and
cannot be accessed outsi
de that schame.
Syntax:
CREATE S
YNONYM synonym_name for table_name;
Level 9 - Views
--> It is advanced of Synonyms.
--> It is a Virtual table to hid
e the base table and it works like a mirror image of the table.
-->
? Simple View
? Complex View
? Force View
? Vertical View
? Horizantal View
? Functional View
? Partition View
? Inline View
? Materialized View
Level 10 - Indexes

? Simple Index
? Complex Index
? Unique Index
? Functional Index
? Bitmap Index
Level 11 - Sub Queries
? Simple Sub Query
? Co Related Sub Query
Level 12 - Clusters
Level 13 - Sequences
-------------SQL FUNCTIONS:
-------------1. Number Functions
2. String Functions
3. Date Functions
4. Conversion Functions
5. General Functions
6. Aggregate Functions
----------------Number Functions:
----------------1. POWER: POWER(a,b)
eg:
POWER(2,4)

= 8

select power(2,10) from dual;

Potrebbero piacerti anche