You are on page 1of 21

DMS-22319 Prof. A. A.

Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
Unit 4: PL/SQL Programming

(16 Marks)
PL/SQL
PL/SQL stands for Procedural Language/Structured Query Language.
It is a programming language which allows the user to write the program to do the various
operations on the databases.
PL/SQL Block Structure:
The parts of PL/SQL block structure are-
1. Declaration
2. Execution
3. Exception
The basic units of PL/SQL are procedures and functions.

[DECLARE
……..declarations]
BEGIN
…….statements
[EXCEPTION
……….handlers]
END;

Fig: PL/SQL Block Structure

1. Declaration:
In this part the variable declaration is done.
Ex: i number;
OR
i number: =1;
2. Begin:
In this part the execution statements are written.
Ex: dbms_output.put_line(‘welcome to SQL’);
3. Exception:
In this part the exceptions due to the BEGIN block can be caught and exception handling
is done to execute the program.
Exceptions are designed to detect and handle run time errors.
Ex: begin
….statements;
exception
When zero_divide then
dbms_output.put_line(‘Number cannot be divided by zero’);
1
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
CONDITIONAL CONTROL

1. IF THEN ELSE ENDIF


The if then else end if is used to check the conditions.
If the condition given in if part is true, then the statement in the if block gets executed.
Otherwise the statements in the else block gets executed.

Syntax: if condition then


statement;
else
statement;
end if;

Example: Find out whether the number is odd or even.

SQL> declare
2 a number;
3 begin
4 a:=&a;
5 if (mod(a,2)=0) then
6 dbms_output.put_line(a||'is even number');
7 else
8 dbms_output.put_line(a||'is odd number');
9 end if;
10 end;
11 /

Enter value for a: 12


old 4: a:=&a;
new 4: a:=12;
12 is even number

SQL> /
Enter value for a: 1
old 4: a:=&a;
new 4: a:=1;
1 is odd number

2
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
2. NESTED IF STATEMENTS
Syntax: if <condition1> then
<statement1>;
else
if <condition2> then
<statement2>;
else
<else statement>;
end if;
end if;

Example: comparison of three numbers.


1 declare
2 a number;
3 b number;
4 c number;
5 begin
6 a:=&a;
7 b:=&b;
8 c:=&c;
9 if (a>b and a>c) then
10 dbms_output.put_line(a ||'is'||'a greatest number');
11 else
12 if(b>a and b>c) then
13 dbms_output.put_line(b ||'is'||'a greatest number');
14 else
15 if(c>a and c>b) then
16 dbms_output.put_line(c ||'is'||'a greatest number');
17 else
18 dbms_output.put_line('All numbers are equal');
19 end if;
20 end if;
21 end if;
22* end;
23 /
Output 1:
Enter value for a: 12
old 6: a:=&a;
new 6: a:=12;
Enter value for b: 13
old 7: b:=&b;
new 7: b:=13;
Enter value for c: 14
old 8: c:=&c;
new 8: c:=14;
14 is a greatest number

3
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
Output 2:
Enter value for a: 1
old 6: a:=&a;
new 6: a:=1;
Enter value for b: 1
old 7: b:=&b;
new 7: b:=1;
Enter value for c: 1
old 8: c:=&c;
new 8: c:=1;
All numbers are equal

4
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
ITERATIVE CONTROL
For the repetition purpose iterative control is used.

1. SIMPLE LOOP
Syntax: loop
Statements;
End loop;

Example:
declare
i number:=0;
begin
loop
dbms_output.put_line(i);
i:=i+5;
exit when i>20;
end loop;
end;
/
Output:
0
5
10
15
20

5
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)

2. WHILE LOOP
The WHILE loop is used to iterate the statements till a particular condition is true.

Syntax:
while(condition)
statements;
incrementer/decrementer;
end loop;

Example: print sum of 1 to 10 numbers.


declare
num number;
i number;
begin
num:=0;
i:=1;
while i<=10
loop
num:=num+i;
i:=i+1;
end loop;
dbms_output.put_line('The sum of 1 to 10 numbers is: '||num);
end;

Output: The sum of 1 to 10 numbers is: 55

3. FOR LOOP
The FOR loop is used to repeat the statements given within it.

Syntax: for counter in [reverse]lowerbound..upperbound


loop
sequence of statements;
end loop;

Example: print 1 to 10 numbers using for loop.

declare
i number;
begin
for i in 1..10
loop
dbms_output.put_line(i);
end loop;
end;

6
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
Output:
1
2
3
4
5
6
7
8
9
10

Example: print odd numbers between 1 and 10 using for loop.

declare
i number;
begin
for i in 1..10
loop
if(mod(i,2)=1) then
dbms_output.put_line(i);
end if;
end loop;
end;

Output:
1
3
5
7
9

7
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
SEQUENTIAL CONTROL

1. GO TO statement
The go to control is used to transfer the control or to change the sequence of the instructions.

Example:
declare
i number;
begin
for i in 1..10
loop
dbms_output.put_line(i);
if i=5 then
goto caught;
end if;
end loop;
<<caught>>
dbms_output.put_line(‘The I is caught’);
end;

(when i is equal to 5 then program stops and output is as following)

Output
1
2
3
4
5
The i is caught

8
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
EXCEPTION HANDLING
Exceptions are designed to detect and handle run time errors.
When error occurs, the control of the program is given or passed to the exception section.

Different exceptions:

Sr. Exception Description


No.
1. NO_DATA_FOUND When SELECT statement cannot return any
rows.
2. PROGRAM_ERROR PL/SQL has an internal problem.
3. STORAGE_ERROR Program ran out of memory.
4. TOO_MANY_ROWS When SELECT statement returns multiple
rows instead of one.
5. ZERO_DIVIDE Program tried to divide by zero.
6. LOGIN_DENIED Program tried to log onto RDMS with
invalid username or password.

Two types of exception:


1. Predefined exceptions.
2. User defined exceptions.

1. Predefined exceptions:
Predefined exceptions are exceptions that are already defined by oracle.
Predefined exceptions are ZERO_DIVIDE, TOO_MANY_ROWS, etc.

Example: declare
a number;
b number;
c number:=1;
begin
a:=&a;
b:=&b;
c:=a/b;
dbms_output.put_line('Result is: '||c);
exception
when zero_divide then
dbms_output.put_line('Number cannot be divided by zero');
end;
(The program raises the pre-defined exception zero_divide when user tried
to divide by zero.)

9
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
Output:

Enter value for a: 12


old 6: a:=&a;
new 6: a:=12;
Enter value for b: 2
old 7: b:=&b;
new 7: b:=2;
Result is: 6
Output:
Enter value for a: 12
old 6: a:=&a;
new 6: a:=12;
Enter value for b: 0
old 7: b:=&b;
new 7: b:=0;
Number cannot be divided by zero

2. User-defined exceptions:
A user-defined exception is an error that is defined by the program (user).
User-defined exceptions are defined are declared in the declarative section of the
PL/SQL block.
Example: declare
empname emp.ename%type;
salary emp.sal%type;
less_sal exception; /user defined exception
begin
select ename, sal into empname, salary from emp where ename=’rahul’;
if salary < 10000 then
raise less_sal;
else
dbms_output.put_line(‘salary is greater than 10000’);
end if;
exception
when less_sal then
dbms_output.put_line(‘salary is less than 10000’);
end;
(The program raises the user-defined exception less_sal when salary of
‘rahul’ is less than 10000.)
Output
salary is less than 10000
10
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
CURSORS
SQL statements are processed in a specific area called as context area. The information
required to complete the processing and a pointer are present in the context area.

Cursors are like array that stores the data. Cursors are like single dimension array or double
dimension array.

Cursor data type is used when we need to take out or fetch number of values of the same
column or multiple columns of even multiple rows at a time from the table.

Types of cursor:

1. REF cursor.
2. Dynamic cursor.
3. Static cursor.

Static Cursors:

In static cursor the select statements are known at the compile time.

Types of static cursor

a. Implicit cursor.
b. Explicit cursor.
a. Implicit cursor:
Implicit cursors are internal cursors used by SQL. They are executed and used by SQL
internally.
Implicit cursors are known as default cursor as they are in built. When user executes DML
statements like INSERT, UPDATE, DELETE the implicit cursors are used.
Implicit cursors are system generated cursors.
Ex: select * from emp_details where sal>5000;
Ex: implicit cursor in PL/SQL
declare
begin
update emp_details set sal=sal+5000 where empno=111;
dbms_output.put_line(sql%rowcount);
end;

Oracle defines some attributes while using implicit cursors:


1. %FOUND
This attribute returns TRUE if DML statement affect minimum one row.
This attribute returns FALSE if DML statement does not return single row.
Format: SQL%FOUND

11
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
2. %NOTFOUND
This attribute returns FALSE if DML statement affect minimum one row.
This attribute returns TRUE if DML statement does not return single row.
Format: SQL%NOTFOUND
3. %ROWCOUNT
This attribute returns the number of rows that are affected by DML statements.
Ex:
declare
rows number(5);
begin
update emp_details set sal=sal+1000;
if sql%notfound then
dbms_output.put_line('none salaries are updated');
elsif sql%found then
rows:=sql%rowcount;
dbms_output.put_line('salaries of'||rows||'updated');
end if;
end;

Output: Salaries of 8 employee are updated.

b. Explicit cursor:
Explicit cursors are not in built. They are defined by the users.
Explicit cursors can use four attributes like ISOPEN, FOUND, NOTFOUND and ROWCOUNT.
Syntax: cursor_name%attribute
The attributes are as follows:
1. %ISOPEN
Returns TRUE if cursor is open and returns FALSE if cursor is not open.
2. %FOUND
This attribute returns TRUE if DML statement affect minimum one row.
This attribute returns FALSE if DML statement does not return single row.
Returns invalid cursor if cursor is closed.
3. %NOTFOUND
This attribute returns FALSE if DML statement affect minimum one row.
This attribute returns TRUE if DML statement does not return single row.
Views NULL before fetching first row.
4. %ROWCOUNT
This attribute returns the number of rows that are affected by DML statements.

12
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
Steps to create Explicit Cursor:

a. Declaring cursor:
Cursor is declared in the declaration section.
Syntax: cursor <cursor_name>is<select query>;
Ex: cursor a is select ename from emp_details where empno=3;
b. Opening cursor:
After declaring the cursor, the cursor needs to open.
Syntax: open <cursor_name>;
Ex: open a;
c. Fetching a record from cursor:
Once the cursor is declared and opened, we need to get records or rows from the
cursor. These records are accessed using the FETCH statement.
Syntax: fetch <cursor_name> into <variable_list>;
Ex: fetch a into name;
d. Closing cursor:
Once the cursor is opened and processing is over, we need to close it.
Syntax: close <cursor_name>;
Ex: close a;

Example of Explicit cursor in PL/SQL:


declare
name emp_details.ename%type;
cursor a is select ename from emp_details where empno=3;//cursor declaration
begin
open a;//opening the cursor
loop
fetch a into name;//fetching the rows from cursor
update emp_details set comm=3000 where empno=3;
exit when a%notfound;
dbms_output.put_line('record updated');
end loop;
close a;//closing the cursor
end;

13
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
PROCEDURES
A procedure can be defined as a subprogram that performs a specific task or action.

CREATING THE PROCEDURE:


Syntax: create or replace procedure <procedure_name> [parameter_list] is
<local_declaration>;
Begin
(executable statements);
[exception](exception handlers)
End;
Example:

create or replace procedure checksal(no number) is sal1 number;


begin
select sal+comm into sal1 from emp_details where empno=no;
if (sal1>30000) then
dbms_output.put_line('salary and commission greater than 30000');
else
dbms_output.put_line('salary and commission less than or equal to 30000');
end if;
exception
when no_data_found then
dbms_output.put_line('no data found');
end;
Procedure created.

EXECUTING THE PROCEDURE:


Syntax: exec <procedure_name>(parameters);

Ex 1:
SQL> declare
begin
checksal(3);
end;
salary and commission greater than 30000

Ex 2:
SQL> declare
begin
checksal(101);
end;
salary and commission less than or equal to 30000

14
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
Ex 3:
SQL> declare
begin
checksal(5);
end;
no data found

DELETING THE PROCEDURE:

A procedure can be dropped using DROP PROCEDURE command.

Syntax: drop procedure <procedure_name>;

Ex: drop procedure checksal;

PL procedure to display odd number between 10 to 50.

SQL> create or replace procedure disp_odd1 is i number;


begin
for i in 1..10
loop
if (mod(i,2)=1) then
dbms_output.put_line(i);
end if;
end loop;
end;
/

Procedure created.

SQL> exec disp_odd;//execute the stored procedure


Output:
1
3
5
7
9

15
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
PL/SQL procedure to display Addition of 2 numbers

create or replace procedure add11(a number, b number) is c number;


begin
c:=a+ b;
dbms_output.put_line ('Addition is:'||c);
end;
SQL> /

Procedure created.

SQL> exec add11(100,100);


Addition is:200

PL/SQL procedure successfully completed.

Advantages of stored procedures:


1. Procedures reduce the usage of network between clients and servers.
2. Procedures can get access to the specific part and does the specific task.
3. Procedures offer more security.
4. While using the stored procedures, the development time can be reduced.
5. The cost of development can be decreases.

16
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)

FUNCTIONS
The function is subprogram that returns value to calling program.
The function is a subprogram that is used for the purpose of code reusability.
The difference between the procedures and functions is that, a procedure cannot return a
value but function can return the value.

CREATING FUNCTION:
Syntax: create or replace function <function_name>[arguments] return datatype is variable
declarations;
begin
executable code;
exception
executable code;
end;

Example:
SQL> create or replace function fun1(minsal number,maxsal number) return number
is a number;
begin
select count(*) into a from emp_details where sal between minsal and maxsal;
return a;
end;
Function created.

EXECUTING FUNCTION:

SQL> declare
count1 number;
begin
count1:=fun1(15000,20000);
dbms_output.put_line('No. of records are:'||count1);
end;
/
Output:
No. of records are: 5

DELETING FUNCTION:

Syntax: drop function <function_name>;


Ex: drop function fun1;

17
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)

Advantages of functions:
1. Code reusability feature can be used.
2. It saves time and cost.
3. Increases the flexibility of the program.
4. Memory space required is less.

PL/SQL Program to perform addition of 2 numbers


create or replace function add1(a number, b number) return number
is c number;
begin
c:=a+b;
return c;
end;
/
Executing the function
declare
aa number;
begin
aa:=add1(100,100);
dbms_output.put_line('addition is:'||aa);
end;
/
Difference between PL/SQL Functions and Procedures:

PL/SQL Functions PL/SQL Procedures

Functions can return a value. Procedures cannot return a value.

Functions can be called or used by SQL Procedures cannot be called or used by SQL
statements. statements.

Function is not a precompiled execution plan. Procedure is a precompiled execution plan.

Syntax: create or replace function Syntax: create or replace procedure

18
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
TRIGGERS
Triggers can be referred as stored procedures that are fired or executed when an INSERT,
UPDATE or DELETE statement is given against the associated table.

The triggers are used for following purposes:

1. To execute data automatically.


2. To implement integrity constraint.
3. To customize security authorization.
4. To maintain duplicate table.
5. To check the data modifications.

CREATING TRIGGERS:

Syntax: create or replace trigger <trigger_name>[before/after] [insert/delete/update] on

<table_name> [for each statement/for each row][when <condition>];

Example:
create or replace trigger trg1 before delete on emp_details
declare
begin
raise_application_error(-20000,'can not delete the record');
end;
Trigger created.

SQL> delete from emp_details where empno=3;


delete from emp_details where empno=3
*
ERROR at line 1:
ORA-20000: cannot delete the record
ORA-06512: at "SYSTEM.TRG1", line 3
ORA-04088: error during execution of trigger 'SYSTEM.TRG1'

Types of triggers:

1. ROW triggers
2. STATEMENT triggers
3. BEFORE triggers
4. AFTER triggers

19
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
1.ROW trigger:

ROW trigger can be executed or fired every time when table is affected.
Example:
create or replace trigger trg2 before update on emp_details for each row
declare
begin
raise_application_error(-20001,'can not update record');
end;
Trigger created.

SQL> update emp_details set sal=sal+1000 where empno=3;


update emp_details set sal=sal+1000 where empno=3
*
ERROR at line 1:
ORA-20001: can not update record
ORA-06512: at "SYSTEM.TRG2", line 3
ORA-04088: error during execution of trigger 'SYSTEM.TRG2'

2.STATEMENT trigger:
STATEMENT trigger is used or fired single time inspite of considering the numbers of rows
present in the table that are affected or row that are not affected.

3.BEFORE and AFTER triggers:


The time must be defined at the time of creating the trigger.
The timing could be before or after the triggering statement.
BEFORE and AFTER are useful for both row and statement triggers.
BEFORE trigger defines an action before DDL command is executed.
AFTER trigger defines an action after DDL command is executed.

DELETING TRIGGER:

Syntax: drop trigger <trigger_name>;


Example: drop trigger trg1;

Difference between Triggers and Procedures:

Triggers Procedures
Triggers are stored procedures used for raising Procedures are sub programs generally
the user defined errors. written for business logic.
Triggers have events and related actions. Procedures does not have events and related
actions.
Triggers are executed when a particular SQL Procedures are executed when they are
command is executed. called.
Triggers does not have in, out parameters. Procedures have in, out parameters.
Syntax: create or replace trigger Syntax: create or replace procedure

20
DMS-22319 Prof. A. A. Nibe
Lecturer, Computer, Vikhe Patil Polytechnic (0030)
Assignment

1. Write a program to display 10 reverse numbers. Use for loop. (4)


2. Explain with suitable example if then else endif statement in PL/SQL. (4)
3. Write a program to display 1 to 7 numbers. (4)
4. What is cursor? Explain the types of cursor. (4)
5. What statement is used to display the output in PL/SQL. (2)
6. Write a program to display the odd numbers between 50 and 100. (4)
7. What is trigger? Explain with its types. (4)
8. Write a program to compare three numbers. (4)
9. Consider the structure: emp (empno, ename, sal)
Write PL/SQL program to update the salary by 500 of rahul.
10. Explain exception handling with its types. (4)
11. Write any two pre-defined exceptions. (2)
12. Explain procedure with example. (4)
13. Explain functions with example. (4)
14. Compare between functions and procedures. (4)
15. Explain the PL/SQL block structure. (4)

21

You might also like