0% found this document useful (0 votes)
39 views89 pages

PLSQL Training Notes

Uploaded by

Venkat Giri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
39 views89 pages

PLSQL Training Notes

Uploaded by

Venkat Giri
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 89

Email: - mailankitnarula@gmail.

com

1|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
PL/SQL Training Notes
PL/SQL is an extension of Structured Query Language (SQL) that is used in Oracle. Unlike
SQL, PL/SQL allows the programmer to write code in a procedural format. Full form of
PL/SQL is “Procedural Language extensions to SQL”.

Advantage of SQL: -

1) We can use programming features like IF statement, Loops etc


2) PL/SQL helps in reducing network traffic.
3) We have user defined error messages by using exception handling.
4) We can save the code in database for repeated execution.
5) We can perform related actions using triggers.

Following are the different type of PL/SQL units: -

1. PL/SQL block
2. Function
3. Package
4. Package body
5. Procedure
6. Trigger

PL/SQL Basic Syntax

We will discuss the Basic Syntax of PL/SQL which is a block-structured language. This
means that the PL/SQL programs are divided and written in logical blocks of code. Each
block consists of three sub-parts −

2|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
S.no Sections & Description

Declare section: -It is used to declare the local variables, cursor, exceptions etc.
1) All the lines between declare and begin is called declare section. This section is
optional.

Begin Section: – The actual task which should be done is written in the executable
2) section. All the lines between begin and exception keyword is call executable
section. This section is mandatory.

Exception Section: -IF an exception is raised in the executable section, controls


3) enter into exception section. All the lines between exception and end is called
exception section. This section is optional.

Every PL/SQL statement ends with a semicolon (;) & Forward Slash (/) . PL/SQL blocks
can be nested within other PL/SQL blocks using BEGIN and END. Following is the basic
structure of a PL/SQL block −

Declare

(declarations section)

Begin

(executable command(s))

Exception

(exception handling)

End;

Set Serveroutput on; — in SQL * Plus before first PL/SQL Command

DBMS Output on – in SQL Developer

3|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Simplest PL/ SQL Block: -

Begin

(executable command(s))

End;

Example :-

Write a program to display 'HELLO WORLD': -

Begin

Dbms_output.put_line ('Hello World');

End;

The Oracle dbms_output.put_line is a procedure allows you to write data to flat file or
to direct your PL/SQL output to a screen.

Write a program to display ‘HELLO WORLD’ & ‘Thank You’ : –

Begin

dbms_output.put_line ('Hello World');

dbms_output.put_line ('Thank You');

End;

4|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
PL/SQL Variables

In PL/SQL, a variable is a meaningful name of a temporary storage location that supports


a particular data type in a program. The name of a PL/SQL variable consists of a letter
optionally followed by more letters, numerals, dollar signs, underscores, and number
signs and should not exceed 30 characters. By default, variable names are not case-
sensitive. You cannot use a reserved PL/SQL keyword as a variable name.

Variable Declaration in PL/SQL

PL/SQL variables must be declared in the declaration section or in a package as a global


variable. When you declare a variable, PL/SQL allocates memory for the variable’s value
and the storage location is identified by the variable name.

The syntax for declaring a variable is : −

<Variable name > <datatype><size>;

Write a PL/SQL block to calculate sum of two numbers.

For this program, we need 3 Variables, so we need declare section.

Declare
A number (3);
B number (3);
C number (3);
Begin
A := 10;
B := 20;
C := a +b;
dbms_output.put_line ('The sum is '||C);
End;
/

5|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
In the above program, there are two important points to learn.

1) : = is assignment operator, which is used to assign value from the right hand side to
the variable in the left hand side.
2) || (Pipe) is concatenation operator.

We can also declare the values in declare section.

Declare
A number (3):= 10;
B number (3):= 20;
C number (3);
Begin
C := a +b;
dbms_output.put_line (c);
End;
/

In the above program, we have hard coded the value 10 and 20 in the program. Instead
of hard coding the value, we can accept the values from the user. For this we need to
use Ampersand Operator

Sign of Ampersand operator: - &

Just like in other programming languages, in PL/SQL also, we can take input from the
user and store it in a variable.

Ampersand operator (&) is used to accept value from the user.

6|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Declare
A number (3);
B number (3);
C number (3);
Begin
dbms_output.put_line ('Welcome');
A :=&a; — taking input for variable A
B :=&b; — taking input for variable B
C := a +b;
dbms_output.put_line ('The Sum is '||c);
End;
/

Enter a value for A: 40

Enter a value for B: 30

Output :- The sum is 70

We can also declare the Ampersand operator in declare section.

Declare
A number (3):=&a;
B number (3):=&b;
C number (3);
Begin
C := a +b;
dbms_output.put_line (c);
End;
/

7|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
SQL Commands In PL/SQL

SQL have 5 Sub Languages.


 DDL commands can work in PL/SQL Block but with execute immediate.
 DML commands can work normally in PL/SQL Block.
 DRL command can work in PL/SQL Block but with INTO Clause.
 TCL commands can work normally in PL/SQL Block.
 DCL commands cannot work in PL/SQL Block.

Create table
Student (Rollno number (4),
Name varchar2 (10),
Marks number (3));

Insert Commands In PL/SQL Block :-

Begin
Insert into student values (101,'Arun', 76);
Insert into student values (102,'Karan', 87);
Insert into student values (103,'Vipan', 60);
End;
/
Other DML Commands & TCL Commands.

Begin
Insert into student values (104, ‘Vijay’, 40);
Update student set marks = 80 where rollno =101;
Delete from dept Where rollno = 103;
Commit;
End;
/

DML Commands will only get PL/SQL procedure successfully completed.


8|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Select Statement in PL/SQL Block :-

Begin
Select * from emp;
End;
/

You Will get an error :- PLS-00428: an INTO clause is expected in this SELECT statement.

Every Select Statement in PL/SQL block/executable section should have INTO Clause.

PL/SQL SELECT INTO statement is the simplest and fastest way to fetch a single row
from a table into variables. The following illustrates the syntax of the PL/SQL SELECT
INTO statement:

SELECT
select_list
INTO
variable_list
FROM
table_name
WHERE
condition;

In this syntax, the number and type of columns in the variable_list must match those of
the select_list. Besides the WHERE clause, you can use other clauses in the SELECT
statement such as INNER JOIN, GROUP BY, HAVING, and UNION.

The following program assigns values from the emp table to PL/SQL variables using the
SELECT INTO clause of SQL −

9|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Write a PL/SQL Block to display sal of ALLEN: –

Declare
A number (4);
Begin
Select sal into a from emp Where ename = 'ALLEN';
dbms_output.put_line (a);
End;
/

Write a PL/SQL Block to display sal & Job of ALLEN: –

Declare
A number (4);
B varchar2 (15);
Begin
Select sal, job into a, b from emp where ename = 'ALLEN';
dbms_output.put_line (a||' '||b);
End;
/

Write a PL/SQL Block to display loc of TURNER: –

Declare
A varchar2 (10);
Begin
Select d.loc into a from emp e, dept d where e.deptno = d.deptno and e.ename
='TURNER';
dbms_output.put_line (a);
End;
/

10 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Write a PL/SQL Block to display Annual sal of KING: –

Declare
A number (10);
Begin
Select sal*12 into a from emp where ename='KING';
dbms_output.put_line (a);
End;
/

In all the above examples we give variables name as A / B is not a good practice in we
need to give proper name so that we can guess with the name for which column we
use the variable.

Declare
v_sal number(4);
v_job varchar2 (15);
Begin
Select sal, job into v_sal, v_job from emp where ename = ‘ALLEN’;
dbms_output.put_line (v_sal ||’ ‘||v_job);
End;
/

PL/SQL Variables Attribute

In PL/SQL program, one of the most common tasks is to select values from columns in a
table into a set of variables. In case the data types of columns of the table changes, you
have to change the PL/SQL program to make the types of the variables compatible with
the new changes.
PL/SQL provides you with a very useful feature called PL/SQL Variables Attribute /
Variable Anchors. It refers to the use of the %TYPE keyword to declare a variable with
the data type is associated with a column’s data type of a particular column in a table.
11 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Using %Type attribute : –

Using %Type attribute is used to declare the local variables.

Instead of hard coding the data type and size for local variable, we can use %TYPE
attribute.

Syntax : – <var_name> <table_name.col_name%type>;

We can also use synonyms name on behalf of table name.

Example:-

v_sal number (4); – we are hard coding data type and size.

v_sal emp.sal%type; — The datatype of ename column of emp table is applicable to the
local variable.

Declare
v_sal emp.sal%type;
v_job emp.job%type;
Begin
Select sal, job into v_sal, v_job from emp where ename = 'ALLEN';
dbms_output.put_line (v_sal ||' '||v_job);
End;
/

12 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Using %row type attribute: –

A row type variable is capable of holding complete row of table.

Syntax : – <var_name> <table_name %rowtype>;

Example : - Display the details of Employee 7521.

Declare
V_emp emp%rowtype;
Begin
dbms_output.put_line ('Welcome');
Select * into v_emp from emp where empno =7521;
Dbms_output.put_line (v_emp.empno);
Dbms_output.put_line (v_emp.ename);
Dbms_output.put_line (v_emp.job);
Dbms_output.put_line (v_emp.hiredate);
Dbms_output.put_line (v_emp.sal);
dbms_output.put_line (‘Thank You’);
End;
/

PL/SQL Conditions

Decision-making structures require that the programmer specify one or more conditions
to be evaluated or tested by the program, along with a statement or statements to be
executed if the condition is determined to be true, and optionally, other statements to
be executed if the condition is determined to be false.

Following is the general form of a typical conditional (i.e., decision making) structure
found in most of the programming languages −

13 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com

S.no Statement & Description


IF – THEN statement The IF statement associates a condition with a sequence of
statements enclosed by the keywords THEN and END IF. If the condition is true,
1)
the statements get executed and if the condition is false or NULL then the IF
statement does nothing.
IF-THEN-ELSE statement. IF statement adds the keyword ELSE followed by an
alternative sequence of statement. If the condition is false or NULL, then only the
2)
alternative sequence of statements get executed. It ensures that either of the
sequence of statements is executed.
3) IF-THEN-ELSIF statement It allows you to choose between several alternatives.

IF Then Statement :–

The IF statement associates a condition with a sequence of statements enclosed by the


keywords THEN and END IF. If the condition is TRUE, the statements get executed, and if
the condition is FALSE or NULL, then the IF statement does nothing.

Syntax :-

IF condition THEN
{…statements to execute when condition is TRUE…}
END IF;

14 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example : -

Declare
A number (3) := 5;
Begin
dbms_output.put_line ('Welcome');
If a = 10 then
dbms_output.put_line ('Hello1');
End if;
dbms_output.put_line ('Thank You');
End;
/

Every IF should have its own end.

When the above code is executed at the SQL prompt, it produces the following result −

Welcome
Thank You

IF-THEN-ELSE statement : –

IF-THEN statements can be followed by an optional sequence of ELSE statements, which


execute when the condition is FALSE.

Syntax :-

IF condition1 THEN
{…statements to execute when condition1 is TRUE…}
ELSIF condition2 THEN
{…statements to execute when condition2 is TRUE…}
END IF;

15 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example :-

Declare
A number (3) := 5;
Begin
dbms_output.put_line ('Welcome');
If a = 10 then
dbms_output.put_line ('Hello1');
Else
dbms_output.put_line ('Hello2');
End if;
dbms_output.put_line ('Thank You');
End;
/

When the above code is executed at the SQL prompt, it produces the following result −

Welcome
Hello2
Thank You

IF-THEN-ELSIF statement : –

The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF…ELSE statement. The ELSIF clause
lets you add additional conditions.

16 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax : -

IF condition1 THEN
{…statements to execute when condition1 is TRUE…}
ELSIF condition2 THEN
{…statements to execute when condition2 is TRUE…}
ELSE
{…statements to execute when both condition1 and condition2 are FALSE…}
END IF;

Example :-

Declare
A number (3) := 30;
Begin
dbms_output.put_line ('Welcome');
If a = 10 then
dbms_output.put_line ('Hello1');
Elsif a =20 then
dbms_output.put_line ('Hello2');
Else
dbms_output.put_line ('Hello3');
End if;
dbms_output.put_line ('Thank You');
End;
/
When the above code is executed at the SQL prompt, it produces the following result −

Welcome
Hello3
Thank You

Try All these Examples with Ampersand operator (&) in Variables.


17 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
PL/SQL Loops

There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a
function is executed first, followed by the second, and so on.

Programming languages provide various control structures that allow for more
complicated execution paths.

A loop statement allows us to execute a statement or group of statements multiple


times and following is the general form of a loop statement in most of the programming
languages −

Types Of Loops In PL/SQL.

 Simple/ Basic Loops


 While Loops
 For Loops

Simple/ Basic Loops

This loop statement is the simplest loop structure in PL/SQL. The execution block starts
with keyword ‘LOOP’ and ends with the keyword ‘END LOOP’.

18 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax : -

LOOP
<Execution block starts>
<EXIT condition based on developer criteria>
<Execution block ends>
END LOOP;

Example :-

Declare
A number := 1;
Begin
dbms_output.put_line ('Welcome');
Loop
dbms_output.put_line ('Hello1');
End loop;
dbms_output.put_line ('Thank you');
End;
/

Note : - Basic loop statement with no EXIT keyword will be an INFINITE-LOOP that will
never stop. Here in this example as you can see we do not have any exit statement to
terminate the loop. This means that if we execute this program then the execution will
keep on printing till we halt it manually.

In this case Oracle PL/SQL gives us clause to terminate the loop

1. Exit When

Exit clause will terminate the loop when Exit condition is evaluated to be true.

19 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example With Exit Clause : -

Declare
A number := 1;
Begin
dbms_output.put_line (‘Welcome’);
Loop
dbms_output.put_line (‘Hello1’);
Exit when a = 3;
A := a +1;
End loop;
dbms_output.put_line (‘Thank you’);
End;
/

While Loops: -

A WHILE LOOP statement in PL/SQL programming language repeatedly executes a target


statement as long as a given condition is true.

Syntax: -

WHILE <EXIT condition>


LOOP
<Execution block starts>
.
<Execution block ends>
END LOOP;

20 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example : -

Declare
A number := 1;
Begin
dbms_output.put_line ('Welcome');
While a <=3 loop
dbms_output.put_line ('Hello1');
A := a+1;
End loop;
dbms_output.put_line ('Thank You');
End;
/

For Loops : -

“FOR LOOP” statement is best suitable when you want to execute a code for a known
number of times rather than based on some other conditions.
In this loop, the lower limit and the higher limit will be specified and as long as the loop
variable is in between this range, the loop will be executed.
The loop variable is self-incremental, so no explicit increment operation is needed in this
loop. The loop variable need not to be declared, as it is declared implicitly.

Syntax:-

FOR <loop_variable> in <lower_limit>.. <higher_limit>


LOOP
<Execution block starts>
.
<execution_block_ends>
END LOOP;
/
21 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example :-

Declare
A number;
Begin
dbms_output.put_line ('Welcome');
For a in 1 .. 4 loop
dbms_output.put_line ('Hello1');
End loop;
dbms_output.put_line ('Thank You');
End;
/

In for loops, the loop variable will be declared implicitly.

Begin
dbms_output.put_line ('Welcome');
For a in 1..4 loop
dbms_output.put_line ('Hello1');
End loop;
dbms_output.put_line ('Thank You');
End;
/

Reverse FOR LOOP Statement :-

By default, iteration proceeds from the initial value to the final value, generally upward
from the lower bound to the higher bound. You can reverse this order by using the
REVERSE keyword. In such case, iteration proceeds the other way. After each iteration,
the loop counter is decremented.

22 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line ('value of a: ' || a);
END LOOP;
END;
/

Nested Block & variable scope

Write a block in a block is called nested block.

Syntax: -

Declare
……………. Parent Block (Inner Block)
Begin
…………….
Declare
…………..
Begin Child Block (Inner Block)
…………
End;
End;
/

23 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example 1 : -

Declare
A number (3) := 100;
Begin
Dbms_output.put_line ('Welcome');
Dbms_output.put_line (a);
Declare
B number (3) := 50;
Begin
Dbms_output.put_line ('Hello');
Dbms_output.put_line (B);
End;
Dbms_output.put_line ('Thank You');
End;
/

Example 2 : -

Declare
A number (3):= 100;
Begin
Dbms_output.put_line ('Welcome');
Dbms_output.put_line (a);
Declare
v_emp emp%rowtype;
Begin
Select * into v_emp from emp where empno =7521;
Dbms_output.put_line ('Hello');
Dbms_output.put_line (v_emp.empno);
Dbms_output.put_line (v_emp.ename);
Dbms_output.put_line (v_emp.job);
24 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Dbms_output.put_line (v_emp.hiredate);
Dbms_output.put_line (v_emp.sal);
End;
Dbms_output.put_line ('Thank You');
End;
/

Inner Block variables cannot access in outer block & outer block variables access in
inner block.

Example 3 : - Outer variable access in inner block.

Declare
v_emp emp%rowtype;
Begin
Select * into v_emp from emp where empno =7521;
Dbms_output.put_line (‘Hello’);
Dbms_output.put_line (v_emp.empno);
Declare
A number (3):= 100;
Begin
Dbms_output.put_line (‘Welcome’);
Dbms_output.put_line (a);
Dbms_output.put_line (v_emp.sal);
Dbms_output.put_line (‘Thank You’);
End;
End;
/

25 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example 4 : - Inner Block variables cannot access in outer block.

Declare
A number (3):= 100;
Begin
Dbms_output.put_line ('Welcome');
Dbms_output.put_line (a);
Declare
v_emp emp%rowtype;
Begin
Select * into v_emp from emp where empno =7521;
Dbms_output.put_line (v_emp.empno);
End;
Dbms_output.put_line (v_emp.sal);
Dbms_output.put_line ('Thank You');
End;
/

Exceptions

Till now we are working in declare & Begin Section now are going to learn how to use
the exception section.

An exception is an error condition during a program execution. PL/SQL supports


programmers to catch such conditions using EXCEPTION block in the program and an
appropriate action is taken against the error condition.

Run Time errors are called exception. Exceptions are also called exception handlers.

26 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Declare
v_sal number(4);
Begin
dbms_output.put_line (‘welcome’);
Select sal into v_sal from emp where empno = 1111;
dbms_output.put_line (v_sal);
dbms_output.put_line (‘Thank You’);
End;
/

Note : - PL/SQL block is terminated abnormally, when select stmt does not return any
row.

Declare
v_sal number(4);
Begin
dbms_output.put_line ('welcome');
Select sal into v_sal from emp where deptno = 30;
dbms_output.put_line (v_sal);
dbms_output.put_line ('Thank You');
End;
/

Note : - PL/SQL block is terminated abnormally, when select statement returns more
than one row.

27 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax : –

Declare

(declarations section)

Begin

(executable command(s))

Exception

When <Exception handler> then

………………..

End;

Types of exceptions: -
1) Pre-defined exceptions
2) Non- Pre Defined exceptions
3) User Defined Exceptions

Pre Defined Exceptions : -

This Exception will have exception name and number.

Types of Pre-defined exceptions: -

1) No_Data_found
2) Too_Many_Rows
3) Zero_Divide
4) Value_Error
5) Dup_val_on_index
28 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
No_Data_Found : -This exception is raised when select does not return any row in
PL/SQL Block.

Declare
v_sal number(4);
Begin
dbms_output.put_line (‘Welcome’);
Select sal into v_sal from emp where empno = 1111;
dbms_output.put_line (v_sal);
dbms_output.put_line (‘Thank You');
End;
/

Note : - In the above program, we get the output 'Welcome'& error.


This means that program execution is started.
As we don’t have any employee with empno 1111, select stmt does not return any row.
When select stmt does not return any row, NO_DATA_FOUND exception is raised.

Important: -Once an exception is raised, control will not execute the remaining
statement of executable section, searches for Exception section.
As we do not have exception section in the program, it is terminated abnormally.
We can make sure that the program is completed normally by catching the exception
using Exception section.

Example : -

Declare
v_sal number(4);
Begin
dbms_output.put_line ('Welcome');
Select sal into v_sal from emp where empno = 1111;
dbms_output.put_line (v_sal);
29 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
dbms_output.put_line ('Thank You');
Exception
When No_data_found then
Dbms_output.put_line ('Invalid Employee Number');
End;
/

Too_Many_Rows : - This exception is raised when select statement returns more than
one rows.

Declare
V_sal emp.sal%type;
Begin
dbms_output.put_line('Welcome');
Select sal into V_Sal from emp where deptno=10;
dbms_output.put_line('The sal is '||V_sal);
dbms_output.put_line('Thank You');
End;
/

As we get the output ‘Welcome’, this means that program execution is started.
As the select statement returns more than one row, TOO_MANY_ROWS exception is
raised.
As we know, Once an exception is raised control will not execute the remaining lines of
executable section, searches for the Exception section.
As we do not have exception section, program is terminated abnormally.
We can avoid abnormal termination of the program by catching the Exception.

30 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example : -

Declare
V_sal emp.sal%type;
Begin
dbms_output.put_line('Welcome');
Select sal into v_Sal from emp where deptno=10;
dbms_output.put_line('The sal is '||V_sal);
dbms_output.put_line('Thank You');
Exception
When TOO_MANY_ROWS then
dbms_output.put_line( 'Select statement returns more than one row');
End;
/

Zero Divide : - This exception is raised, when we divide a number by zero.

Declare
A number (4);
Begin
dbms_output.put_line('Welcome');
A:= 10/0;
dbms_output.put_line(a);
dbms_output.put_line('Thank You');
End;
/

In the above program, as we are dividing by zero, ZERO_DIVIDE exception is raised.


As we are not catching the exception, program is terminated abnormally.
As a developer, we need to make sure that programs are completed successfully at any
case.
SO we need to handle exception which is raised by using the Exception Section.

31 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example : -

Declare
A number (4);
Begin
dbms_output.put_line('Welcome');
A: = 10/0;
dbms_output.put_line(a);
dbms_output.put_line('Thank You');
Exception
When ZERO_DIVIDE then
dbms_output.put_line('DO not divide by Zero');
End;
/

Value_Error : - This exception is raised, when the value is returned does not match with
the data type variables.

Declare
V_ename number (10);
Begin
dbms_output.put_line('Welcome');
Select ename into V_ename from emp where empno = 7369;
dbms_output.put_line('The employee name is '||V_ename);
End;
/

As the select statement returning char value, it cannot be stored in variable of number
data.
In this case VALUE_ERROR exception is raised.
As we are not catching the exception, program is terminated abnormally.
We can avoid abnormal termination of the program by catching the exception using
Exception Section.
32 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example : -

Declare
V_ename number (10);
Begin
dbms_output.put_line('Welcome');
Select ename into V_ename from emp where empno = 7369;
dbms_output.put_line('The employee name is '||V_ename);
Exception
When VALUE_ERROR then
dbms_output.put_line('Please check the data type of the local variables');
End;
/

Dub_val_on_index : - This exception is raised when we try to insert a duplicate value on


a primary key or unique key.

Create the following table : -

Create table student (Rollno number (3) primary key, namevarchar2 (20),marks number
(3));

Insert a row in the table & Commit : -

Insert into student values (101,'arun', 40);


Commit;

33 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Adding Duplicate row in table in PL/SQL block.

Begin
dbms_output.put_line ('welcome');
Insert into student values (101,'vijay', 50);
dbms_output.put_line ('Thank you');
End;
/

As we are inserting a duplicate value in a primary key column, DUP_VAL_ON_INDEX


exception is raised. As we are not catching the exception program is terminated
abnormally.

We can avoid abnormal termination of the program by catching the exception.

Example : -

Begin
dbms_output.put_line ('Welcome');
Insert into student values (101,'vijay', 50);
dbms_output.put_line ('Thank you');
Exception
When DUP_VAL_ON_INDEX then
dbms_output.put_line('Do not insert duplicate value in a primary key');
End;
/

34 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Exception Name Exception Number Exception Message
No_Data_Found ORA -1403 No data found
exact fetch returns more
Too_Many_Rows ORA -1422 than requested number of
rows
Zero_Divide ORA -1476 divisor is equal to zero
PL/SQL: numeric or value
Value_Error ORA -6502 error: character to number
conversion error
Dub_val_on_index ORA -0001 unique constraint violated

When others handlers: - When others can handle any type of exception.
Universal handlers called others.

Example 1 : -

Declare
A number (4);
Begin
dbms_output.put_line('Welcome');
A: = 10/0;
dbms_output.put_line(a);
dbms_output.put_line('Thank You');
Exception
When others then
dbms_output.put_line('Pl check the code');
End;
/

Note :- Exception that is raised is ZERO_DIVIDE.


We do not have ZERO_DIVIDE handler in the above program, but When Others can
handler can handle this exception.
35 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example 2 : -

Declare
l_sal emp.sal%type;
Begin
dbms_output.put_line(‘Welcome’);
Select sal into l_Sal from emp where deptno=10;
dbms_output.put_line(‘The sal is ….’||l_sal);
dbms_output.put_line(‘Thank You’);
Exception
When others then
dbms_output.put_line(‘Pl check the code’);
End;
/

We Can also Write Two Exceptions: -

Example 3 : -
Declare
v_sal number(4);
Begin
dbms_output.put_line (‘Welcome’);
Select sal into v_sal from emp where empno = 1111;
dbms_output.put_line (v_sal);
dbms_output.put_line (‘Thank You’);
Exception
When No_data_found then
Dbms_output.put_line (‘Invalid Employee Number’);
When others then
Dbms_output.put_line (‘please check Employee ID’);
End;
/
36 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example 4 : -

Declare
v_sal number(4);
Begin
dbms_output.put_line ('Welcome');
Select sal into v_sal from emp where empno = 1111;
dbms_output.put_line (v_sal);
dbms_output.put_line ('Thank You');
Exception
When others then
Dbms_output.put_line ('Please check Employee ID');
When No_data_found then
Dbms_output.put_line ('Invalid Employee Number');
End;
/

In Example 4 you will get the below mention error

ERROR at line 9:
ORA-06550: line 9, column 1:
PLS-00370: OTHERS handler must be last among the exception handlers of a block
ORA-06550: line 0, column 0:
PL/SQL: Compilation unit analysis terminated

Note :- OTHERS handler must be last among the exception handlers of a block. IF not we
will get compilation error.

37 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Error Reporting Functions : -This function is used in When others clause, to identify the
exception which is raised.

Two Types of Error reporting Functions : -


1) SQL Code : -Will return exception number.
2) SQLERRM : -Will return exception number &message.

Example 1 : -

Declare
v_sal emp.sal%type;
A number (2);
Begin
dbms_output.put_line ('Welcome');
Select sal into v_sal from emp where empno = &empno;
dbms_output.put_line ('The sal is ….'||v_sal);
A := 10/0;
dbms_output.put_line('Welcome');
Exception
When others then
dbms_output.put_line (SQLCODE);
dbms_output.put_line (SQLERRM);
dbms_output.put_line ('please check the code');
End;
/

Try This Example with correct & incorrect employee number.

38 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Example 2 : -

Declare
v_sal number(4);
Begin
dbms_output.put_line (‘Welcome’);
Select sal into v_sal from emp where empno = 1111;
dbms_output.put_line (v_sal);
dbms_output.put_line (‘Thank You’);
Exception
When others then
dbms_output.put_line (SQLCODE);
dbms_output.put_line (SQLERRM);
Dbms_output.put_line (‘please check Employee ID’);
End;
/

Note :- For No_Data_Found SQL Code will return 100 still a mystery.

Non Pre Defined Exceptions : -

This exception will have exception number but does not have exception name.

Create table student2 (sno number (3) primary key, sname varchar2 (20),marks number
(3));

Insert into student2 values (101, 'arun', 40);


Insert into student2 values (102, 'varun', 50);
Insert into student2 values (103, 'kiran', 60);

39 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Create table library2 (roll_no number(3) references student2(sno), book_name varchar2
(20));

Insert into library2 values (101,'Java');


Insert into library2 values (102,'C++');
Insert into library2 values (102,'Oracle');

Commit;

Begin
dbms_output.put_line('Welcome');
Delete from student2 where sno =101;
dbms_output.put_line('Thank You');
End;
/

ORA-02292: integrity constraint (HR.SYS_C0012221) violated - child record found


This exception is raised when we try to delete from row from the parent table if
corresponding row exists in the child table.

Note:- We are deleting the row from the parent table and the corresponding row exists
in the child table. So exception is raised. The exception which is raised in the above
program is ORA-2292. This exception does not have any name. This is an example of non
-predefined exception.

The following steps are followed to handle non-pre defined exception.

Step 1: Declare the exception


Step 2: Associate the exception
Step 3: Handle then exception.

40 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax :-

Step 1 : Declare the exception


<Exception_name> Exception;
Step 2 : Associate the exception
raise_application_error (<exception_no>, <Exception_name>);
Step 3 : Handle the exception
Exception
When <Exception_name> then
…………
End;
/

In the following program, we perform the three step process to handle Non-pre
defined exceptions.

Declare
MY_EX1 Exception;
Raise_application_error (-2292, MY_EX1);
Begin
dbms_output.put_line ('Welcome');
Delete from student2 where sno =101;
dbms_output.put_line ('Thank You');
Exception
When MY_EX1 then
dbms_output.put_line ('Cannot delete from the parent table');
End;
/

41 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
User Defined Exceptions : -

These exceptions are defined and controls by the developers.

Following steps are to be followed to handle user defined exceptions.

Step 1: Declare the exception


Step 2: Raise the exception
Step 3: Handle the exception

Example : -

Declare
l_sal emp.sal%type;
My_ex1 exception;
Begin
dbms_output.put_line(‘Welcome’);
Select sal into l_sal from emp where empno =7902;
If l_sal> 2000 then
Raise my_ex1;
End if;
dbms_output.put_line(‘the sal is ‘||l_sal);
Exception
When my_ex1 then
dbms_output.put_line (‘Sal is too high’);
When others then
dbms_output.put_line(‘Pl check the code’);
End;
/

42 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Cursors

Cursor is a memory location which is used to run SQL commands.

There are two types cursors

1) Implicit Cursors
2) Explicit Cursors

Implicit Cursors : -

Implicit cursors are automatically created by Oracle whenever an SQL statement is


executed, when there is no explicit cursor for the statement. Programmers cannot
control the implicit cursors and the information in it. Whenever a DML statement
(INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this
statement. For INSERT operations, the cursor holds the data that needs to be inserted.
For UPDATE and DELETE operations, the cursor identifies the rows that would be
affected.

All the activated related to cursor like

i) Opening the cursor


ii) Processing the data in the cursor
iii) closing the cursor
Are done automatically. Hence these cursors are called implicit cursors.

43 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Implicit Cursor Attributes: -

1) SQL%ISOPEN: -It is a Boolean attribute. It always returns false. It is not used in


programming as it always returns false.

2) SQL%FOUND: -It is a Boolean attribute.


Returns TRUE -- if the SQL command effects the data.
Returns FALSE -- if the SQL commands do not effects the data.

3) SQL%NOTFOUND: -It is a Boolean attribute


Returns TRUE -- if the SQL command do not effects the data.
Returns FALSE -- if the SQL command effects the data
Note: It is exactly opposite to SQL%FOUND

4) SQL%ROWCOUNT: -Returns no of rows affected by the SQL command.

Using SQL%Found : -

Begin
Update emp set sal=2000 where empno=1111;
End;
/

By looking at the above message, we cannot know whether your update command is
affecting the data or not.
To overcome this problem, we have SQL%FOUND attribute.
Have a look at this program

44 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Begin
Update emp set sal=2000 where empno=1111;
If SQL%FOUND then
dbms_output.put_line('Update is successfull');
Else
dbms_output.put_line('Update is failed');
End if;
End;
/

Using SQL%NotFound : -SQL%NOTFOUND is exactly opposite to SQL%FOUND.

Begin
Update emp set sal=2000where empno=1111;
If SQL%NOTFOUND then
dbms_output.put_line('Update is failed');
Else
dbms_output.put_line('Update is successful');
End if;
End;
/

Using SQL%RowCount : -SQL%ROWCOUNT attribute is used to find the no of rows


affected by SQL command.

Begin
Update emp set sal=2000 where deptno=10;
End;
/
Output : -PL/SQL Procedure successfully completed.

In the above example we are not able to see how many rows are updated by PL/SQl
block
45 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
For this we can use SQL%rowcount.

Begin
Update emp set sal=2500 where deptno=10;
dbms_output.put_line(SQL%ROWCOUNT||’ rows updated’);
End;
/

SQL%ISOPEN: -

Begin
Update emp set sal =2500 where empno = &empno;
IF SQL%isopen then
Dbms_output.put_line ('Cursor is open');
Else
Dbms_output.put_line ('Cursor is closed');
End if;
End;
/

Enter the correct & Incorrect employee number. Try with both you will get the same
output cursor is closed because SQL%Isopen always return False.

Explicit Cursors: -

Explicit cursors are programmer-defined cursors for gaining more control over the
context area. An explicit cursor should be defined in the declaration section of the
PL/SQL Block. It is created on a SELECT Statement which returns more than one row.

46 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Write a query to display Name & sal of department no 10: -

Declare
V_ename emp.ename%type;
V_sal emp.sal%type;
Begin
Select ename,v_sal into v_ename,v_sal from emp where deptno =10;
Dbms_output.put_line(v_ename||' '||v_sal);
End;
/

we are getting the error.

ERROR at line 1:
ORA-01422: exact fetch returns more than requested number of rows
ORA-06512: at line 5

Because above program is written more than one row for this we are going to use
explicit cursors.

The syntax for creating an explicit cursor is −

CURSOR cursor_name IS select_statement;

Steps to use explicit cursors : -

Step 1: Declare the cursor


Step 2: Open the cursor
Step 3: Fetch the data from the cursor to the local variables
Step 4: Close the cursor

47 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax of the above four steps :

Declaring the Cursor : – Declaring the cursor defines the cursor with a name and the
associated SELECT statement. For example

Step 1: Declaring the cursor


Cursor < cursor_name>
Is < select statement>

Opening the Cursor : – Opening the cursor allocates the memory for the cursor and
makes it ready for fetching the rows returned by the SQL statement into it. For example,
we will open the above defined cursor as follows −

Step 2: Open the cursor


Open < cursor_name >;

Fetching the Cursor : – Fetching the cursor involves accessing one row at a time. For
example, we will fetch rows from the above-opened cursor as follows −

Step 3 : Fetch the data from the cursor to the local variables
Fetch < cursor_name > into < var1 >, < var2>,….., < varn >;;

Closing the Cursor : – Closing the cursor means releasing the allocated memory. For
example, we will close the above-opened cursor as follows −

Step 4 : close the cursor


Close < cursor_name>;

48 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Explicit cursor attributes : -

There are four explicit cursor attributes

1) %ISOPEN:
It is a Boolean attribute.
Returns TRUE -- if the cursor is open
Returns FALSE -- if the cursor is closed

2) %FOUND:
It is a Boolean attribute
Returns TRUE -- if the fetch stmt is successful
Returns FALSE -- if the fetch stmt fails

3) %NOTFOUND:
It is Boolean attribute
Returns TRUE -- if the fetch stmt fails.
Returns FALSE -- if the fetch stmt is successful
Note: 1) It is exactly opposite to %FOUND attribute
2) This attribute is used to break the loop of the fetch stmt.

4) %ROWCOUNT:
Returns no of rows fetched by the fetch stmt.

49 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
%NotFound

Write a query to display Name &sal of department no 10: -

Declare
v_ename emp.ename%type;
V_sal emp.ename%type;
Cursor c1
Is select ename,sal from emp where deptno = 10;
Begin
Open c1;
Loop
Fetch c1 into v_ename,V_sal;
Exit when c1%notfound;
dbms_output.put_line( v_ename||' '||V_sal );
End loop;
Close c1;
End;
/

Note : -When we open a cursor memory location is created, loaded with data written by
the select statement having cursor pointer pointing to first row this status is called
active data structure.

we are also used loops in cursors for execute the cursor more than one time.

Write a PL/SQL procedure to display dname, loc from dept table

Declare
Cursor c1
Is select dname ,loc from dept;
V_dname dept.dname%type;
V_loc dept.loc%type;
Begin
Open c1;
50 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Loop
Fetch c1 into V_dname, V_loc;
Exit when c1%notfound;
dbms_output.put_line(V_dname||' '||V_loc);
End loop;
Close c1;
End;
/

Write a program to display name, salary, hire date from emp table having salary more
than 2000.

Declare
v_ename emp.ename%type;
v_sal emp.sal%type;
v_hiredate emp.hiredate%type;
Cursor c1
Is select ename,sal,hiredate from emp where sal >2000;
Begin
Open c1;
Loop
Fetch c1 into v_ename,v_sal, v_hiredate;
Exit when c1%NOTFOUND;
dbms_output.put_line(v_ename||' '||v_sal||' '||v_hiredate);
End loop;
Close c1;
End;
/

51 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
%FOUND

%FOUND is Opposite to %NOT FOUND.

Using %Is Open: -

Declare
Cursor c1
Is select ename from emp;
Begin
Open C1;
If C1%isopen then
DBMS_output.put_line('Cursor is open');
Else
DBMS_output.put_line('Cursor is closed');
End if;
End;
/

Using % row count: -

Write a program to display first three employees’ names from emp table using row
count.

Declare
v_ename emp.ename%type;
Cursor cur
Is select ename from emp;
Begin
Open cur;
Loop
Fetch cur into v_ename;
52 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Exit when cur%rowcount =4;
dbms_output.put_line (v_ename);
End loop;
Close cur;
End;
/

Cursor For loops: -

It is shortcut way of writing explicit cursors.


When we use cursor for loops, following steps are not required.

1) Open the cursor


2) Fetch stmt
3) Exit when condition
4) Closing the cursor
5) Declaring the local variables

Steps to be followed in cursor for loops.

1) Declare the cursor


2) Mention cursor in For Loops

Syntax for Loops

1) Declare the Cursor

Cursor cursor_name
Is select statement;

53 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
2) Mention cursor in For Loops

FOR record_name IN cursor_name


LOOP
process the row…
END LOOP;

Example : -

Write a query to display Name & sal of department no 10: -

Declare
Cursor cur
Is select ename,sal from emp where deptno =10;
Begin
For a in cur loop
Dbms_output.put_line(a.ename||' '||a.sal);
End loop;
End;
/

Write a program to display all the columns & rows from dept table using cursor for
loops: -

Declare
Cursor cur
Is select * from dept;
Begin
For a in cur loop
Dbms_output.put_line(a.deptno||' '||a.dname||' '||a.loc);
End loop;
End;
/
54 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Procedures
A procedure is a named PL/SQL Block which is complied and stored in the database for
repeated execution.

Syntax to create procedure: -

Create or replace Procedure <Procedure_name> (var1 in /out/ inout data type,var2 in


/out/ inout data type)
Is
Declaration section
Begin
……….
Exception
……………..
End;
/

Syntax to execute the procedure: –

Exec Procedure_name;

Example: -

Create a procedure to display Hello World: -

Create or replace procedure Pro


Is
Begin
Dbms_output.put_line('Hello World');
End;
/

55 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Execute the Above procedure:-

Exec pro;

A procedure can have three types of parameters: -

1) In Parameter
2) Out Parameter
3) In Out Parameter

In parameter are used to accept values from the user.

CREATE OR REPLACE PROCEDURE procedure_name (Param_name1 IN data type,


param_name2 IN data type)

param_name1, param_name2… are unique parameter names.

Data Type – defines the data type of the variable.

IN – is optional, by default it is an IN type parameter.

Create a procedure which accepts two numbers and display its sum: -

Create or replace procedure Add_num (a in number,b in number)


Is
C number (3); to get the 2 values we need to declare
the local variable
Begin
C :=a+b;
Dbms_output.put_line('The sum is '|| C);
End;
/
56 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
To execute the procedure: -

Exec add_num (10, 20);

Create a procedure which accepts an empno and increments his salary by 1000.

Create or replace procedure Inc_sal (v_empno in emp.empno%type)


Is
Begin
Update emp set sal = sal +1000 where empno = v_empno;
End;
/

To execute the procedure: -

Exec inc_sal (7900);

Create a procedure which accepts empno and display name and salary : -

Create or replace procedure dis_salary (v_empno in emp.empno%type)


Is
V_ename emp.ename%type;
V_sal emp.sal%type;
Begin
Select ename,sal into v_ename , v_sal from emp where empno = v_empno;
Dbms_output.put_line (v_ename||' '||v_sal);
End;
/

To execute the procedure: -

Exec dis_salary (7900);

57 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
We improved the above procedure code by using %type attribute in procedure
parameters.

Create or replace procedure dis_salary (v_empno in emp.empno%type)


Is
V_ename emp.ename%type;
V_sal emp.sal%type;
Begin
Select ename,sal into v_ename , v_sal from emp where empno = v_empno;
Dbms_output.put_line (v_ename||' '||v_sal);
Exception
When no_data_found then
Dbms_output.put_line('Employee number is invalid');
End;
/

Execute the Above procedure: -

Exec dis_salary (7900);


Exec dis_salary (44444);

Create a procedure which accepts deptno and display average salary of every
department number

Create or replace procedure avg_sal (v_deptno in emp.deptno%type)


Is
v_sal number(6,2);
Begin
Select avg(sal) into v_sal from emp where deptno = v_deptno;
dbms_output.put_line (v_sal);
End;
/

58 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Execute the Above procedure:-

Exec avg_sal(10);
Exec avg_sal(30);
Exec avg_sal(90);

Note: – We can improve this procedure with exception section but group function does
not return the exception/error only return value.

Create a procedure which accepts deptno and display ename and salary of employees
working in that department from emp table with cursor for loops.

We use cursor for loops when we need to more than one row.

Create or replace procedure Display_details (v_deptno in emp.deptno%type)


Is
Cursor c1
Is
Select ename,sal from emp where deptno = v_deptno;
Begin
For a in c1 Loop
Dbms_output.put_line(a.ename||' '||a.sal);
End loop;
Exception
When no_data_found then
dbms_output.put_line (‘please check the department number');
End;
/

Execute the Above procedure:-


Exec display_details(10);
Exec display_details(20);
59 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Create below mention table for more examples : -

Create table marks (rollno number (4),name varchar2 (10), maths number (3),
English number(3),science number(3));

Insert into MARKS values (101,'Ankit',78,98,67);


Insert into MARKS values (102,'Sunil',87,56,87);
Insert into MARKS values (103,'Kiran',97,87,89);

Need result like average marks of 101 is ….

Create a procedure to get the average marks of every student: -

Create or replace procedure cal_avg


Is
Cursor c1
Is select * from marks;
v_avg number(6,2);
Begin
For a in c1 loop
v_avg := (a.maths+a.english+a.science)/3;
dbms_output.put_line('Average marks of '|| a.rollno||' is '||v_avg);
End loop;
End;
/

Execute the Above procedure : -

Exec cal_avg(101);

60 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
We can call procedure from another procedure.

Sub procedure : – A procedure inside another procedure is called as Sub procedure.

Create a simple demo procedure : –

Create or replace procedure demo


Is
Begin
dbms_output.put_line('This is from demo');
End;
/

Create a simple sample procedure with above demo procedure included : –

Create or replace procedure sample


Is
Begin
dbms_output.put_line ('This is from sample');
Demo; ——–Above procedure
Demo;
dbms_output.put_line ('Thank You');
End;
/

Execute the Above procedure : -

Exec Sample;

Exec will write only when SQL Prompt or outside the procedure.

61 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
How to drop a procedure: -

Syntax : -

Drop procedure procedure_name

Example : -

Drop procedure demo;

Relationship is established between two procedures this is called dependence.

Dropping demo procedure will make sample procedure invalid.

By recreating the demo procedure sample procedure will be valid automatically.

Create a procedure inside a procedure.

Create or replace procedure test


is
procedure sample
is
begin
dbms_output.put_line('This is from sample');
end;
begin
dbms_output.put_line('This is from test');
sample;
end;
/

In the above example procedure sample is called as Sub procedure.

A Sub procedure can be invoked from the main procedure only.

62 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
To execute the procedure :-

Exec test;

We cannot invoke the Sub procedure independently.

The following command will give error.

EXEC sample;

We can call multiple procedures at a time using PL/SQL block.

Syntax : -

Begin
Procedure name;
Procedure name;
Procedure name;
End;
/

Example : -

Begin
Sample;
Add_num(10,20);
Dis_salary(7900);
End;
/
How to check all the procedure in the database: –

In SQL*Plus

Select object_name from user_objects where OBJECT_TYPE =’PROCEDURE’;

63 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
In SQL Developer

we have option on right side where we can click on procedure & see all the names of
the procedure which are available in our database.

How to check source of existing procedure : -

In SQL*Plus

SELECT TEXT FROM USER_SOURCE WHERE NAME ='CHECK_STATUS';

In SQL Developer

Type procedure name and right click then select open declaration.

Create a procedure using Default keyword: –

Create or replace procedure add_num (a in number, b in number default 100, c in


number default 200)
Is
D number
Begin
D := a+b+c;
Dbms_output.put_line ('The Sum is '||D);
End;
/

To execute the procedure :-

Exec add_num(10,20,30);

Exec add_num(10,20);
64 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Note :- Default value is considered if we do not pass any value.

You need to use arrow operator if you pass values to specific parameters.

Exec add_num (a=>10, c =>20);

Default value 100 is considered for parameter b.

Out Parameters : – are used to written the value to the user.

Syntax : –

CREATE OR REPLACE PROCEDURE proc2 (param_name OUT datatype);

The parameter should be explicitly declared as OUT parameter.

Create a procedure which accepts two numbers and written its sum.

Create or replace procedure return_sum( a in number, b in number, c out number)


Is
Begin
C :=a+b;
End;
/

As the procedure is returning a value using OUT parameter,


we need to have a bind variable to catch the value. We need to follow a 3 step process
to execute the above procedure.

65 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Step 1: - Create a bind variable
Step 2: - execute the bind variable
Step 3: - Print the variable

Step 1: creating Bind variable

Var add_num number;

Step 2: Invoking the procedure using bind variable

Exec return_sum(10, 20, :add_num);

Step 3 : – Print the variable in bind variable

Print add_num;

As Procedure is having out parameter we need a variable to catch the value return. This
variable is called bind variable.

To call the procedure return_sum in the PLSQL Block.

Declare
A number;
Begin
Return_sum (10,20, a);
Dbms_output.put_line('The sum is '||a);
End;
/

66 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Create a procedure which accepts a number and get its square. With name ret_square
Means if you enter the value 10 you get the answer 100.

Create or replace procedure ret_square(a in number, b out number)


Is begin
B := a*a;
End;
/

For Execution : –

With Bind Variable.

Step 1 :- Var c number;

Step 2 :- Exec ret_square(5, :c);

Step 3 :- Print c;

With Pl/SQL Block

Declare
C number;
Begin
Ret_square(5,c);
End;
/

67 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
In out parameters : -In out parameters can take both accept as well as return the value
to the user.

Syntax : –
CREATE [OR REPLACE] PROCEDURE proc3 (param_name IN OUT datatype);

Create a procedure which a number and returns its square. With name ret_square2

Create or replace procedure ret_square2 (a in out number)


Is
Begin
A :=a*a;
End;
/

To declare the in out parameters with bind variable: -

1) Create bind variable


2) Initialize bind variable
3) Execute procedure
4) Print variable

Step 1) Create bind variable

Var b number;

Step 2) Initialize bind variable

begin
:b := 7
End;
/
68 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Step 3) Invoke the procedure using bind variable

Exec ret_square2 (:b);

Step 4) Print the value in the bind variable

Print b;

To declare the in out parameters with PLSQL Block: -

Declare
B number:=7;
egin
ret_square2 (b);
dbms_output.put_line(b);
End;
/

How to check all the procedure are available in database.

Select object_name from user_objects where object_type = 'PROCEDURE';

Functions

Function is a PL/SQL block which must and should return single value. Functions are also
called as sub program.

69 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax : -

Create or replace function function_name (var1 data type, var2 data type,Var 3 data
type)
Return data type
Is
Declaration part
Begin
………..
Exception
…………..
End;
/

Create a function which accepts number and return its sum.

Create or replace function add_fun (a number, b number)


Return number
Is
C number;
Begin
C :=a+b;
Return c;
End;
/

70 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
To execute to the function with PLSQL block : -

Declare
N number;
Begin
N := add_fun (10,20);
Dbms_output.put_line ('The sum is '||n);
End;
/

Function will return the value with the select statement.

Select add_fun(10,30) from dual;

Functions can be invoked as part of an expression.

Select 100+add_fun(10,30) from dual;

Create a function which accepts salary and return tax value (7% of sal is tax)

Create or replace function sal_tax (v_sal number)


Return number
Is
V_tax number (6,2);
Begin
V_tax := v_sal*7/100;
Return v_tax;
End;
/

71 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Function will return the value with the Pl/SQL Block.

Declare
N number (6, 2);
Begin
N :=sal_tax(75000);
Dbms_output.put_line ('The tax is '||N);
End;
/

With Select Statement.

Select sal_tax(75000) from dual;

You can use Function with database tables in select statement.

Select empno, ename, sal, sal_tax(sal) from emp;

Have a look at the following function:-

Create or replace function add_num_f2 (a number, b number)


Return number
Is
C number (5);
Begin
Insert into dept values (50,'HR','HYDERABAD');
C :=a+b;
Return c;
End;
/

72 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
To execute to the function with PL/SQL block : –

Declare
N number (5);
Begin
N := add_num_f2(20,40);
dbms_output.put_line('The sum is '||n);
End;
/

To execute to the function with Select Statement: –

Select add_num_f2(30,50) from dual;

Note : - So, functions with dml commands cannot be invoked from select statement&
PLSQL Block.

When we create a function with DML commands it will not give you the error but when
you will execute then it will give you the error but DML command will complete the
operations.

TO see the list of all the functions: -

Select object_name from user_objects where object_type = 'FUNCTION';

To drop a function: -

Drop function <function_name>;

Drop function add_num_f2;

Functions are mainly used for calculation purposes.


Rest of the activities, prefer procedures.

73 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Difference between Procedure and functions: -

Procedure Functions
Not return Value Must Return a value
Cannot be involved from select statement Can be involved from select statement
DML Commands are allowed DML Commands are not allowed

Packages

PL/SQL package is a group of related functions, procedures , cursors , etc. PL/SQL


package is like a library once written stored in the Oracle database and can be used by
many applications.

Creating a package is two step process: -

Create Package Specification (PKS) : -It contains declaration of procedures and


functions.

Create Package Body (PKB) : -It Contains Definition of procedures and functions.

Syntax of Package Specification: -

Create or replace package <package_name>


Is
Declaration of procedures;
Declaration of functions;
End;
/

74 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax of Package body: -

Create or replace package body <package_name>


Is
Definition of procedures;
Definition of functions;
End;
/

Lets create a package with two procedures and function.

Procedure Pro : – To Display Hello World.


Procedure Add_num : – which takes two parameters and display its sum.
Procedure Dis_Salary : – which accepts empno and display sal.
Function Cal_tax : – which accepts sal and returns tax value (7% of sal is tax value ).

Package Specification : –

Create or replace package Test_pkg


Is
Procedure pro;
Procedure Add_num (a number, b number);
Procedure Dis_salary (v_empno emp.empno%type);
Function Cal_tax (v_sal emp.sal%type)
return number;
End;
/

Package Body : –

Create or replace package body test_pkg


is

75 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
procedure Pro
is
begin
dbms_output.put_line('Hello World');
end;
Procedure add_num (a number, b number)
is
c number;
begin
C :=A+B;
dbms_output.put_line('The Sum is '||C);
end;
procedure dis_salary (v_empno emp.empno%type)
is
v_sal emp.sal%type;
begin
select sal into v_sal from emp where empno = v_empno;
dbms_output.put_line('The salary is '||V_sal);
exception
when no_data_found then
dbms_output.put_line( ‘Employee Number is invalid’);
end;
function cal_tax (v_sal emp.sal%type)
return number
is
v_tax number;
begin
v_tax := v_sal *7/100;
return v_tax;
end;
end;
/
76 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
To invoke procedure or function inside a package

Syntax for procedure :- exec package_name.procedure_name;

Syntax for functions : - Select package_name.function_name(value) from table_name;

Invoke Procedure : –

Exec test_pkg.pro;

Exec test_pkg.add_num(10,20);

Exec test_pkg.dis_salary(7900);

Invoke Function : –

Select text_pkg.cal_tax(79000) from dual;

Package cannot be nested. Package body cannot exist without package body
specifications you should follow the order. Package helps in overloading subprograms.

Create a package(Test_pkg2) with two procedures having same name P1 if we enter


one value it give you his square root like you enter 10 you get 100 and if we enter two
values then we get sum of that two values.

Package Specification : –

Create or replace package test_pkg2


is
procedure p1(a number);
procedure p1(a number, b number);
end;
/
77 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Package Body : –

Create or replace package body test_pkg2


is
procedure p1(a number)
is
b number;
begin
b :=a*a;
dbms_output.put_line(b);
end;
procedure p1(a number,b number)
is
c number;
begin
c :=a+b;
dbms_output.put_line(c);
end;
end;
/

Invoke procedure inside a package.

Exec test_pkg2.p1(10);

Exec test_pkg2.p1(10,20);

78 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Important Interview Example : –

Test_PKG3 Specifications Test_PKG3 Body


P1 P1
P2 P2
P3 P3
P4

In Specification we have 3 Procedures But in Body we have 4 procedures.

Can we execute the P4 with exec command?

Subprogram can exist in package body without declaration in specification. This type of
subprogram are called private program.
we cannot execute private procedure directly.
Private procedure can be called by procedures which are mention in PKG specification.
we only execute P4 with some package while creating other procedure written P4 in
that procedure.

To check All Package : –

Select object_name from user_object where object_type=’PACKAGE’;

To drop a package is also a two step process and reverse process: –

Drop package body test_pkg;

Drop package test_pkg;

79 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Triggers

Triggers is a PLSQL block which is executed automatically basic on a event.

Triggering event : -Insert, Update and delete

Trigger Timing : -Before, After and instead of

Syntax : -

Create or replace trigger <Trg_name>


<Timing><event> on <table_name>
Begin
.........
end;
/

Create a trigger which display 'Thank You For Inserting' Message when a row is insert
into the emp table.

Create or replace trigger Tri1


after insert on emp
begin
dbms_output.put_line('Thank You For Inserting');
end;
/

Insert into (empno,ename,sal,deptno) value ('2828','Ankit',1000,20);

If we insert 100 rows then we will get the same output.

80 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
If there is error in insert command then trigger is also failed.

Trigger can be executed on multiple events.

Create or replace trigger Tri1


after insert or update or delete on emp
dbms_output.put_line ('Thank you');
end'
/

Update emp set sal = 3000 where empno=7900;

Delete from emp where empno=2828;

In the above program, we get the same message for all the events.

We can also have different messages to be displayed, basing on the events.

create or replace trigger Tri1


after insert or update or delete on dept
begin
if inserting then
dbms_output.put_line('Thank You for inserting');
elsif updating then
dbms_output.put_line('Thank You for updating');
else
dbms_output.put_line('Thank You for deleting');
end if;
end;
/

Insert into (empno,ename,sal,deptno) value ('2828','Ankit',1000,20);

81 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Update emp set sal = 5000 where empno=7900;

Delete from emp where empno=2828;

In the above program, inserting and updating are the key words which are used to
identify the events.

IF we can use insert, update or delete command with PLSQL Block we get the same
message.

Triggers can be classified into two types, basing on the no of times it is executed.

Statement level triggers: - are executed only once, irrespective of no of rows affected
by the event. By Default every trigger is a statement level trigger.

Row level triggers: - are executed for every row affected by the event.

To create a row level trigger, we need to use for-each-row clause.

Create or replace trigger trg1


After update on emp for each row
Begin
dbms_output.put_line('Thank you for updating');
End;
/

Update emp set sal=2000 where deptno=10;

These trigger will execute for every row affected by the event. IF n rows are affected,
trigger will execute n number of time. These kinds of triggers are called row level
triggers.

You cannot change the table name from existing trigger.


82 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Triggers are used to enforce business rules by using :OLD and :NEW qualifiers.

Create a trigger which will restrict insert operations on emp table if salary is more
than 5000.

Create or replace trigger trg4


Before insert on emp for each row
begin
if :new.sal>5000 then
raise_application_error (-20150,'Salary cannot be more than 5000');
end if;
end;
/

Insert into emp (empno,ename,sal) values (2828,'Ankit',8000);

We can also use check constraint but trigger will give you proper message. A non-
technical person can easily understand the error.

Raise_application_error : - is used to throw error number and message to the calling


environment.Raise_application_error is also have an ability to stop the event.

Error number should be in the range of -20000 to -20999. you can use any number.
Error message should be less than or equal to 2000 characters.

Create a trigger which will restrict insert operations if loc is delhi in dept table.

Create or replace trigger res_ins


Before insert on dept for each row
Begin
If :new.loc = 'DELHI' then
raise_application_error(-20149,'The location should not be delhi');
83 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
End if;
End;
/

Think that company is having a lot of loss so company need to remove some employee
and they need to create a trigger so that they don't delete the president from the emp
table.

Create a trigger which restricts delete operations when job is president.

Create or replace trigger del_pre


Before delete on emp for each row
Begin
If :old.job='PRESIDENT' then
raise_application_error(-20282,'Not able to delete the President');
End if;
End;
/

:New is used when we need to insert the row.


:OLD is used when we need to delete the row.

Instead of triggers: - are helpful to perform DML operations on complex view.

Create or replace view emp_dept_v


As
Select e.empno, e.ename, e.sal, e.deptno, d.dname, d.loc
From emp e, dept d where e.deptno = d.deptno;

Insert into emp_dept_v values (2121,'VIJAY',3000,60,'TRAINING','HYDERABAD');

Generally, we cannot insert row into complex view.


But, by using the instead of triggers, we can do it.
84 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com

Create or replace trigger v_trg


Instead of insert on emp_dept_v for each row
Begin
Insert into dept values (:NEW.deptno,:NEW.dname, :NEW.loc);
Insert into emp (empno, ename,sal, deptno) values
(:NEW.empno,:NEW.ename,:NEW.sal, :NEW.deptno);
End;
/

Insert into emp_dept_v values (2121,'VIJAY',3000,60,'TRAINING','HYDERABAD');

Create a trigger when we insert row in one table then automatically on second table
add these details.

New_Name, OLD_Name, User_Name,Entry_Date,DML

Create First Table: –

CREATE TABLE superheroes (


sh_name VARCHAR2 (15)
);

Create Second Table: –

CREATE TABLE sh_audit(


new_name varchar2 (30),
old_name varchar2 (30),
user_name varchar2 (30),
entry_date varchar2 (30),
Operation varchar2 (30)
85 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
);
CREATE OR REPLACE TRIGGER superheroes_audit
BEFORE INSERT OR DELETE OR UPDATE ON superheroes
FOR EACH ROW
ENABLE
DECLARE
v_user varchar2 (30);
v_date varchar2 (30);
BEGIN
SELECT user, TO_CHAR (sysdate, 'DD/MON/YYYY HH24: MI: SS’) INTO v_user, v_date
FROM dual;

IF INSERTING THEN
INSERT INTO sh_audit (new_name,old_name, user_name, entry_date, operation)
VALUES (:NEW.SH_NAME, Null, v_user, v_date, 'Insert');

ELSIF DELETING THEN


INSERT INTO sh_audit (new_name,old_name, user_name, entry_date, operation)
VALUES (NULL,:OLD.SH_NAME, v_user, v_date, 'Delete');

ELSIF UPDATING THEN


INSERT INTO sh_audit (new_name,old_name, user_name, entry_date, operation)
VALUES(:NEW.SH_NAME, :OLD.SH_NAME, v_user, v_date,'Update');
END IF;
END;
/

Try below mention Row to insert in first table.

INSERT INTO superheroes VALUES ('Superman');

Update the Row.

86 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
UPDATE SUPERHEROES SET SH_NAME = 'Ironman' WHERE SH_NAME='Superman';
Delete the Row.

DELETE FROM superheroes WHERE SH_NAME = 'Ironman';

Now check the Audit table.

Select * from sh_audit;

Synchronized Table Backup Using DML Trigger

When we insert/update/delete row from table 1 then automatically table 2 is


updated.

Create First Table.

CREATE TABLE new_superheroes(


Sh_name VARCHAR2 (30));

Create Second Table As Duplicate.

CREATE TABLE superheroes_backup


AS
SELECT * FROM superheroes WHERE 1=2;

Creating Trigger.

CREATE or REPLACE triggerSh_Backup


BEFORE INSERT OR DELETE OR UPDATE ON superheroes
FOR EACH ROW
ENABLE
BEGIN
IF INSERTING THEN
87 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
INSERT INTO superheroes_backup (SH_NAME) VALUES (:NEW.SH_NAME);
ELSIF DELETING THEN
DELETE FROM superheroes_backup WHERE SH_NAME =:old.sh_name;
ELSIF UPDATING THEN
UPDATE superheroes_backup
SET SH_NAME =:new.sh_name WHERE SH_NAME =:old.sh_name;
END IF;
END;
/

Try to Insert / Update/ Delete the First Table & Check Both the table after every step.

Mutating Trigger: - When triggers makes a recursive called to itself it if called a mutating
trigger.

Table Student Table student_Duplicate


101 Amit 80 101 Amit 80
102 Karan 90 102 Karan 90

When we insert a row in student table then automatically row insert into
student_duplicate.

When we insert a row in student_duplicate table then automatically row insert into
student.

This will give you the error.

Benefits of trigger: -

1) For automatic execution

88 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
2) Triggers are used to enforce business rules.
We can disable the trigger

Disable a trigger: - Alter trigger trigger_name disable;

Enable a trigger: - Alter trigger trigger_name enable;

How to check all the triggers in the database: -

Select object_name from user_objects where OBJECT_TYPE ='TRIGGERS';

Drop a trigger: -

Drop trigger trigger_name;

Example: –

Drop Trigger tri1;

89 | P a g e www.selfonlinetraining.wordpress.com

You might also like