PLSQL Training Notes
PLSQL Training Notes
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. PL/SQL block
2. Function
3. Package
4. Package body
5. Procedure
6. Trigger
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.
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;
3|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Simplest PL/ SQL Block: -
Begin
(executable command(s))
End;
Example :-
Begin
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.
Begin
End;
4|Page www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
PL/SQL Variables
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.
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
Just like in other programming languages, in PL/SQL also, we can take input from the
user and store it in a variable.
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;
/
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
Create table
Student (Rollno number (4),
Name varchar2 (10),
Marks number (3));
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;
/
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;
/
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;
/
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;
/
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 : –
Instead of hard coding the data type and size for local variable, we can use %TYPE
attribute.
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: –
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
IF Then Statement :–
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;
/
When the above code is executed at the SQL prompt, it produces the following result −
Welcome
Thank You
IF-THEN-ELSE statement : –
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
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.
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.
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: -
Syntax: -
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:-
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;
/
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;
/
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;
/
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.
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.
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
………………..
End;
Types of exceptions: -
1) Pre-defined exceptions
2) Non- Pre Defined exceptions
3) User 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;
/
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;
/
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;
/
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;
/
Create table student (Rollno number (3) primary key, namevarchar2 (20),marks number
(3));
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;
/
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;
/
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;
/
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;
/
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.
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;
/
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.
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));
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));
Commit;
Begin
dbms_output.put_line('Welcome');
Delete from student2 where sno =101;
dbms_output.put_line('Thank You');
End;
/
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.
40 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax :-
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 : -
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
1) Implicit Cursors
2) Explicit Cursors
Implicit Cursors : -
43 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Implicit Cursor Attributes: -
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;
/
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;
/
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;
/
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.
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
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 −
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 −
48 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
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
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.
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
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;
/
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 cursor_name
Is select statement;
53 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
2) Mention cursor in For Loops
Example : -
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.
Exec Procedure_name;
Example: -
55 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Execute the Above procedure:-
Exec pro;
1) In Parameter
2) Out Parameter
3) In Out Parameter
Create a procedure which accepts two numbers and display its sum: -
Create a procedure which accepts an empno and increments his salary by 1000.
Create a procedure which accepts empno and display name and salary : -
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 a procedure which accepts deptno and display average salary of every
department number
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 table marks (rollno number (4),name varchar2 (10), maths number (3),
English number(3),science number(3));
Exec cal_avg(101);
60 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
We can call procedure from another 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 : -
Example : -
62 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
To execute the procedure :-
Exec test;
EXEC sample;
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
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.
In SQL*Plus
In SQL Developer
Type procedure name and right click then select open declaration.
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.
Syntax : –
Create a procedure which accepts two numbers and written its sum.
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
Print add_num;
As Procedure is having out parameter we need a variable to catch the value return. This
variable is called bind variable.
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.
For Execution : –
Step 3 :- Print c;
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
Var b number;
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
Print b;
Declare
B number:=7;
egin
ret_square2 (b);
dbms_output.put_line(b);
End;
/
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;
/
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;
/
Create a function which accepts salary and return tax value (7% of sal is tax)
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;
/
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;
/
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 drop a function: -
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
Create Package Body (PKB) : -It Contains Definition of procedures and functions.
74 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Syntax of Package body: -
Package Specification : –
Package Body : –
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
Invoke Procedure : –
Exec test_pkg.pro;
Exec test_pkg.add_num(10,20);
Exec test_pkg.dis_salary(7900);
Invoke Function : –
Package cannot be nested. Package body cannot exist without package body
specifications you should follow the order. Package helps in overloading subprograms.
Package Specification : –
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 : –
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.
79 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Triggers
Syntax : -
Create a trigger which display 'Thank You For Inserting' Message when a row is insert
into the emp table.
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.
In the above program, we get the same message for all the events.
81 | P a g e www.selfonlinetraining.wordpress.com
Email: - mailankitnarula@gmail.com
Update emp set sal = 5000 where empno=7900;
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.
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.
Create a trigger which will restrict insert operations on emp table if salary is more
than 5000.
We can also use check constraint but trigger will give you proper message. A non-
technical person can easily understand the error.
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.
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 when we insert row in one table then automatically on second table
add these details.
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');
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.
Creating Trigger.
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.
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.
Benefits of trigger: -
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
Drop a trigger: -
Example: –
89 | P a g e www.selfonlinetraining.wordpress.com