PLSQL Notes
PLSQL Notes
-----Block
------
-->It is one of the areas which are used to write Programming logic.
-->Block has 3 sections:
1. Declaration Section:
** It is one of the sections which are used to declare variables, cursors and
exceptions 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.
Ex1: DECLARE
_______________
BEGIN
------------END;
Ex2: BEGIN
DBMS_OUTPUT.PUT_LINE("Welcome to E Business
Solutions");
END;
2. Named Block:
** These blocks are having a name and also stored in
database.
Examples : Procedures , Functions, Packages and Triggers etc..
Variable
-->It is one of the memory location which is used to store the data.
-->Generally we declare the variables in declaration section.
-->Variables Support default and not null.
Syntax :Variable_Name
Datatype ( Size );
Ex : Declare
A
Number (5);
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;
---------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
variable.
-->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 : || || vname );
End;
% RowType
-->It is one of thedatatype which is used assign all the column datatypes of table 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.
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;
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
emp.empno=vno;
Dbms_output.put_line(vrec.vname||,||vrec.vsal||,||vrec.vloc);
End;
----------------------Conditional Statements
----------------------1. If Condition
2. If Else Condition
3. Elsif Condition
4. 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;
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. Loop
2. Simple Loop
3. While Loop
4. 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
For
n in 1..10
lowerbound..outerbound
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;
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 record
by record process
---------EXCEPTIONS
----------->Exception is one of the activity which is used to handle the errors at runtime.
Types of Exceptions:
1. Predefined Exception
2. User-defined Exception
3. Un-named Exception
*--> Predefined Exception:
** It is one of the Exception which are defined by Oracle.
** There are about 20 Exceptions defined by Oracle.
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" clause and if requested data not
available in the table, Oracle Server returns an error.
* ERROR is ORA-01403:no data found
* To handle this error we are using NO_DATA_FOUND exception.
Eg:
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP WHERE
EMPNO=1111;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||
I.ENAME);
END;
--Above program will throw no data found exception, we will catch the exception in
below program
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP WHERE
EMPNO=1111;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||
I.ENAME);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE("Employee 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.
DECLARE
I EMP%ROWTYPE;
BEGIN
SELECT * INTO I FROM EMP WHERE DEPTNO=40;
DBMS_OUTPUT.PUT_LINE(I.EMPNO||','||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.EMPNO||','||I.ENAME||','||
I.DEPTNO);
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE("Employee 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 opening the cursor then Oracle server
returns an error.
* ERROR is ORA-01001: Invalid Cursor
* To handle this error we are using INVALID_CURSOR exception.
Eg:
DECLARE
CURSOR C1 IS SELECT * FROM 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.ENAME||','||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 * FROM 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.ENAME||','||I.SAL);
END LOOP;
CLOSE C1;
EXCEPTION
WHEN INVALID_CURSOR THEN
DBMS_OUTPUT.PUT_LINE("Open 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_ALREADY_OPEN exception.
Eg:
DECLARE
CURSOR C1 IS SELECT * FROM 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.ENAME||','||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 * FROM 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.ENAME||','||I.SAL);
END LOOP;
CLOSE C1;
EXCEPTION CURSOR_ALREADY_OPEN THEN
DBMS_OUTPUT.PUT_LINE("Cursor is Open already, Please close before opening
again");
END;
5.INVALID_NUMBER:
----------------*Whenever we try to convert string type to number 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 exception as we are trying to insert
string into NUMBER datatype SAL, we will catch the exception in below program
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 number based on the condition then
Oracle server returns error.
*Whenever we try to store large amount of data than the specified data type size in
variable declaration then Oracle server returns error.
*ERROR is ora-06502: numeric or value error: character to number conversion error
*To handle this error we are using VALUE_ERROR Exception.
Eg1:
DECLARE
Z NUMBER(10);
BEGIN
Z:='&X'+'&Y';
DBMS_OUTPUT.PUT_LINE(Z);
END;
--Above program will throw numeric or value error 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 Server
return a error.
*Error is ORA-01476: divisor is equal to zero
*To handle this error we are using ZERO_DIVIDE
Exception.
Eg1:
DECLARE
A NUMBER(10);
B NUMBER(10):=&B;
C NUMBER(10):=&C;
BEGIN
A:=B/C;
DBMS_OUTPUT.PUT_LINE(A);
END;
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 Section
2. Executable Section
3. Exception Section
Ex:
BEGIN
DECLARE
Z VARCHAR2(3):='ABCD';
BEGIN
Z:='ABCD';
DBMS_OUTPUT.PUT_LINE(Z);
EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.PUT_LINE("INVALID STRING LENGTH");
END;
EXCEPTION
WHEN VALUE_ERROR
THEN
DBMS_OUTPUT.PUT_LINE("THE LENGHT IS MORE");
END;
-->DECLARE EXCEPTION:
--> In
Declare section of the PL?SQL program we are defining our own Exception using
Exception type.
Syntax:
userdefinedexception_name exception;
Ex:
DECLARE
A EXCEPTION;
-->Raise Exception:
-->
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 Exception:
--> We can
also handle user defined exceptions same as predefined exception using 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
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;
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;
***IMP***
-->
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 WHERE
EMPNO=7369;
DBMS_OUTPUT.PUT_LINE(SQLCODE);
DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
***IMP***
-->
-----------------------------> If you want to display your own user defined exception number and
exception message then we can use this raise application error.
Syntax:
raise_application_error (error_number,error_message);
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
EMPLOYEE_ID=I.EMPLOYEE_ID;
END IF;
EXCEPTION
WHEN A THEN
RAISE_APPLICATION_ERROR(-20000,'Salary is already very
high');
END;
-->
UN-NAMED EXCEPTION:
---------------------------
--> In this case we are providing exception names and also associate
this exception name with appropriate error number using exception_init function.
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;
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 process.
--> Procedure are used to improve the performance of business
applications.
--> Every Procedure is having two parts
a) Procedure Specification
-->In procedure Specification
we are specifying name of the procedure and types of the parameters.
b) Procedure Body
--> In procedure body we are
solving actual task.
EX:
CREATE OR REPLACE PROCEDURE P1(P_EMPNO NUMBER)
IS
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.EMPLOYEE_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 for
given Employee_id: '|| P_REC.P_EMP_ID);
END PROC_NAME;
table
----------------------------Method 1 :
EXEC P11(7902);
Method 2 : Begin
P11(7902);
end;
Ex2:
EX:
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 or INOUT
parameters those subprograms are executed using 2 Methods:
BIND VARIABLE:
--> These variables are session
variables
Ex:
VARIABLE B NUMBER;
EXEC P1(10,:b);
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.
BEGIN
SELECT SALARY INTO PSALARY FROM EMPLOYEES WHERE
EMPLOYEE_ID=PEMPLOYEE_ID;
DBMS_OUTPUT.PUT_LINE('Salary of the Employee with Emplpoyee_id:
'||PEMPLOYEE_ID||' is : '||PSALARY);
END;
Executing PROCEDURE:
VARIABLE V NUMBER;
EXEC P3(101,:V);
3) INOUT MODE:
Ex1:
CREATE OR REPLACE
PROCEDURE P1(A IN OUT NUMBER) Is
BEGIN
A:=A*A;
DBMS_OUTPUT.PUT_LINE(A);
END;
VARIABLE A NUMBER;
EXEC :A:=10;
--Assigning value 10 to variable A.
EXEC P1(:A);
DECLARE
A NUMBER(10):=&N;
BEGIN
P1(A);
DBMS_OUTPUT.PUT_LINE(A);
END;
EX2:
CREATE OR REPLACE PROCEDURE
P4(A IN OUT NUMBER) IS
BEGIN
SELECT SAL INTO A FROM EMPLOYEE
WHERE EMPNO=A;
DBMS_OUTPUT.PUT_LINE(A);
END;
:-->FUNCTIONS:
----------------> Function is a named PL/SQL block which is used to Solve
Particular task and by default functions return a single Value.
Ex:
CREATE OR REPLACE FUNCTION F1( A VARCHAR2)
RETURN VARCHAR2
IS
BEGIN
RETURN A;
END;
EXECUTING Function:
1. ANONYMOUS Block:
DECLARE
A
VARCHAR2(10):='WELCOME';
BEGIN
A:=F1('Welcome');
DBMS_OUTPUT.PUT_LINE(A);
END;
2. BIND Variable:
VARIABLE A Varchar2(10);
Begin
:A:=F1('WELCOME');
END;
3. EXEC:
EXEC
DBMS_OUTPUT.PUT_LINE(F1('Welcome'));
4. SELECT:
SELECT F1('WELCOME TO APPS') FROM
DUAL;
NOTE: If we want to return more number of values from Function we are using
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_DEPTNO;
RETUN P_DNAME;
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
*************************************************************************************
*************************************************************************************
*************************************************************************************
*******************
--------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
Invoked.
--> Generally Packages are used to Improve performance of the Application
END;
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;
EXEC PACK1.P1;
(PACKAGE NAME.PROCEDURE NAME)
EX2:
PACK1.P1(10,20,C);
DBMS_OUTPUT.PUT_LINE(C);
END;
LOCAL VARIABLE:
--> It is one of the variable which is used to define 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
EX:
CREATE OR REPLACE PACKAGE PACK4
IS
PROCEDURE P1(A NUMBER, B NUMBER);
PROCEDURE P2(X NUMBER, Y NUMBER);
END;
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 another
procedure then only we are using forward declaration.
--> That means, when we are calling local procedures into
global procedure first we must implement local procedures before calling otherwise
use a forward declaration in package body.
PROCEDURE P2
//Implementing local proc
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('lOCAL
procedure');
END P2;
END;
*************************************************************************************
*************************************************************************************
*************************************************************************************
*******************
-------TRIGGERS
---------> Triggers are also same as Stored Procedures, Triggers are
automatically invoked whenever DML operations are performed against table or a
view.
--> 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
Syntax:
if inserting
then
statements;
elseif
updating then
statements;
elseif
deleting then
statements;
end if;
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;
END IF;
INSERT INTO TEST VALUES (A);
END;
Syntax:
--> :old.column_name
(or)
:new.column_name
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 INSERT
ON EMP
FOR EACH ROW
BEGIN
IF :NEW.SAL<5000 THEN
RAISE_APPLICATION_ERROR(-20123,'SALARY
SHOULD BE MORE THAN 5000');
END IF;
END;
ON DELETE CASCADE:
------------------While deleting a record, if there is dependency of that record in any other table.
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.
Q: Write a PL/SQL Row Level Trigger Whenever user inserting data into ename
column after inserting data must be converted into uppercase.
Q: Write a PL/SQL Row Level Trigger on EMP table by using below Condition?
1. Whenever user Inserting data those values stored in another
table.
2. Whenever user Updating data those values stored in another
table.
3. Whenever user Deleting data those values stored in another
table?
table
MUTATING TRIGGER:
-----------------
*************************************************************************************
*************************************************************************************
*************************************************************************************
*******************
VVIP
-----------COLLECTIONS
------------
-->INDEX BY TABLE:
---------------> This is an User defined type which is used to
store Multiple data items to a Single Unit. Basically this is an Non-constraint table.
--> Generally these tables are used to improve
performance of applications because these tables are stored in Memory area thats
why These tables are also called as Memory Tables.
--> Basically These Table Contains Key Value Pairs,
i.e Value field is Stored in Actual Data and Key field Stored in Indexes.
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;
DECLARE
TYPE T1 IS TABLE OF VARCHAR2(10)
INDEX BY BINARY_INTEGER;
V_T T1;
BEGIN
SELECT ENAME BULK COLLECT INTO
V1 FROM EMP;
FOR I IN V1.FIRST..V1.LAST
LOOP
DBMS_OUTPUT.PUT_LINE(V1(I));
END LOOP;
END;
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+1;
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 COLLECT 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