Unit 4 K PLSQL Programming
Unit 4 K PLSQL Programming
Unit 4 K PLSQL Programming
Kshirsagar
CONTENTS:
4.1 Introduction of PL/SQL: -Advantages of PL/SQL, The PL/SQL Block
Structure, PL/SQL Data Types, Variable, Constant
4.2 Control Structure :- Conditional Control, Iterative Control, Sequential Control.
4.3 Exception handling: -Predefined Exception, User defined Exception.
4.4 Cursors:- Implicit and Explicit Cursors, Declaring, opening and closing cursor,
fetching a record from cursor, cursor for loops, parameterized cursors
4.5 Procedures :- Advantages, Create, Execute and Delete a Stored Procedure
4.6 Functions :- Advantages, Create, Execute and Delete a Function
4.7 Database Triggers :- Use of Database Triggers, Types of Triggers, Create
trigger, delete trigger
Introduction of PL/SQL:
Begin
Exception
[Exception handling errors]
END;
/
Each PL/SQL program consists of SQL and PL/SQL statements which form a
PL/SQL block.
A PL/SQL Block consists of following sections:
The Declaration section: Declaration of memory variables, constants, records,
and cursors used later in begin section. DECLARE keyword is used for
declaration. This section is not mandatory i.e. as needed this section is used.
The Execution section: It starts with the reserved keyword BEGIN and ends with
END .This is mandatory section. It contains SQL executable statements, program
logic code, loops, conditional statements etc. all this in BEGIN...END block.
DECLARE
BEGIN
----------
EXCEPTION
PL/SQL Datatypes:
Variable declaration:
Syntax
variable_name datatype(size) ;
Constant:
Constant declaration:
e.g.
salary_increment CONSTANT number(3):=1000;
varablename datatype(size):=&variablename;
e.g.
n number(10):=&n;
a number(10):=&a;
dbms_output.put_line(‘statement’||variable);
e.g:
dbms_output.put_line(‘Hello world!’); --o/p : Hello world!
Suppose n=5 , so
dbms_output.put_line(n); --o/p: 5
dbms_output.put_line(n||’is positive’); --o/p: 5 is positive
dbms_output.put_line(‘the positive value is’||n); --o/p:the positive value is 5
dbms_output.put_line(‘the value’||n||’is positive’); --o/p:the value 5 is positive
1)IF THEN
SYANTAX:
If condition THEN
Statements;
END IF;
Explanation:
If condition true, then the statements are executed/run. Otherwise IF condition is
false then if statement does nothing i.e control gets out of end if..
e.g.
set serveroutput on;
declare
n number(2):=&n;
begin
if(n>20) then
dbms_output.put_line(n||’ is positive');
end if;
end;
/
o/p:
enter value for n:=10
10 is positive
2)
set serveroutput on;
declare
n number(4):=15; --value of n taken while declaration
begin
if(n<20) then
dbms_output.put_line('n is less than 20');
end if;
end;
/
o/p:
n is less than 20
PL/SQL procedure successfully completed.
If condition THEN
Statement1;
ELSE
Statement2;
END IF;
Explanation:
If condition is true ,then the statement1 executed/run and control goes out of end
if. otherwise if condition is false statement2 executed/run and control goes out of
end if.
e.g.
set serveroutput on;
declare
age number(4):=&age;
begin
if(age>18) then
dbms_output.put_line('you can vote');
else
dbms_output.put_line('you can not vote');
end if;
end;
/
SYCM-Computer Technology Department, SVCP, Pune Page 8
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
o/p
Enter value for age:=23
You can vote
PL/SQL procedure successfully completed.
3) IF THEN ELSE IF
SYANTAX:
If condition1THEN
Statement1;
ELSE IF condition2 THEN
Statement2;
ELSE IF condition3 THEN
Statement3;
ELSE
Statement_n;
END IF ;
END IF:
END IF;
Explanation:
If then else if is used when there are multiple(more than one ) conditions
if condition1 is true then statement1 is execute and control goes out of if, if
condition1 is false then it will check next condition2 if it is true it execute
statement2 and control goes out of if, if condition2 is false it will checks next
conditions , and execute respective statement which condition is true, and control
goes out of if.
if all conditions false then it will execute sttementn in else part. and control goes
out of else.
Example:
1) pl/sql program to check the no. is positive , negative or zero.
set serveroutput on;
declare
n number:=&n;
begin
if (n>0) then
dbms_output.put_line(‘n is positie’);
else if(n<0)
dbms_output.put_line(‘n is negative’);
else
dbms_output.put_line(‘n is zero’);
end if;
end if;
end;
SYCM-Computer Technology Department, SVCP, Pune Page 10
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
/
o/p
Enter value for n: -14
-14 is negative
PL/SQL procedure successfully completed.
o/p
enter value for percentage:65
first class
PL/SQL procedure successfully completed.
e.g.3.
declare
n number(4):=100;
begin
if(n=10) then
dbms_output.put_line('the value of n is 10');
else if(n=20) then
SYCM-Computer Technology Department, SVCP, Pune Page 11
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
o/p:
the value of n is not matching in given conditions
PL/SQL procedure successfully completed.
NESTED IF THEN
Nested if means the if within if
Any number of else if clause can be used with one if.
Each nested if statement must terminate with corresponding end if.
SYNTAX:
if condtion1 then
if condition2 then
statement1;
else
statement2;
end if;
else if condition3 then
statement3;
else
statement_x;
end if;
end if;
Explanation:
If condition1(outer if) is true, it will checks next condition(inner if) condition2, if
condition2 is true ,it execute statement1 and if condition2 is false it execute
statement2.
a number:=&a;
b number:=&b;
c number:=&c;
begin
if a>b then
if a>c then
dbms_output.put_line('a is greater');
else
dbms_output.put_line('c is greater');
end if;
dbms_output.put_line('b is greater');
else
dbms_output.put_line('c is greater');
end if;
end if;
end;
O/P:
Enter value for a: 12
Enter value for b: 14
Enter value for c: 8
b is greater
1)BASIC LOOP:
It encloses sequence of statements in between LOOP and END LOOP.
EXIT or EXIT WHEN statement is required to break the loop.
Syntax:
LOOP
sequence_of_statements;
END LOOP;
Example:
set serveroutput on;
declare
a number:=10;
begin
loop
dbms_output.put_line(a);
a:=a+10;
exit when(a>60);
end loop;
end;
SYCM-Computer Technology Department, SVCP, Pune Page 14
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
/
10
20
30
40
50
60
PL/SQL procedure successfully completed
WHILE condition
LOOP
sequence_of_statements;
END LOOP;
Example:
declare
a number(3):=11;
begin
while a<=20
loop
dbms_output.put_line(a);
a:=a+1;
end loop;
end;
/
o/p:
11
12
13
14
15
16
17
18
19
20
SYCM-Computer Technology Department, SVCP, Pune Page 15
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
Syntax:
FOR counter IN initial_value..final_value
LOOP
sequence_of_statements;
END LOOP;
50
51
52
53
54
55
56
57
58
59
60
PL/SQL allows using one loop inside another loop(like basic,while,for loop)
Syntax:
loop
sequence_of_statements_1;
loop
sequence_of_statements_2
end loop;
end loop;
example:
declare o/p
i number; 1
j number; 2
3
begin
1
for i in 1..3 loop
2
for j in 1..3 loop
3
dbms_output.put_line(j);
1
end loop; 2
end loop; 3
end;
DECLARE
i NUMBER(3);
j NUMBER(3);
BEGIN
i := 2;
LOOP
j := 2;
LOOP
OR ( j = i ) );
j := j + 1;
END LOOP;
IF( j = i )THEN
dbms_output.Put_line(i||' ');
END IF;
i := i + 1;
END LOOP;
END;
CASE:
A case statement uses a selector.
The CASE statement selects one sequence of statements/action to execute
depending on selector.
Here selector is variable or expression.
The case statement checks value of selector one by one from top to bottom and
execute the corresponding statement when it finds valid value of selector And
control goes to end case.
SYNTAX:
CASE selector
When value1 then s1;
When value2 then s2;
When value3 then s3;
.
.
.
.
Else Sn ; … default case
End case;
Here, selector is variable. The value of selector will be checked with values
sequentially as soon as the value of selector is matched, the corresponding
statement of matched value will get execute and control goes out of end case, if no
any values are matched then, it execute statement in else i.e sn.
o/p:
Enter value for daynum: 5
Friday
PL/SQL procedure successfully completed.
e.g. pl/sql program for grade (take value while declaration) using case
statement
declare
grade varchar(15):='A';
begin
case grade
when 'A' then dbms_output.put_line('first class’);
when 'B' then dbms_output.put_line('second class');
when 'C' then dbms_output.put_line('pass');
elsedbms_output.put_line('no value of grade is matching');
end case;
end;
/
o/p: first class
PL/SQL procedure successfully completed.
2) CONTINUE
continue statement skip the current iteration and start the next iteration.
Syntax:
continue;
example:
set serveroutput on;
declare
i number ;
begin
for i in 1..5 loop
if i=3 then
continue;
end if;
dbms_output.put_line(i);
end loop;
end;
/
o/p:
1
2
4
5
e.g :2) PL/SQL program to calculate addition of even numbers between 1 to
10 by skipping odd numbers using continue.
set serveroutput on;
declare
sum number:=0;
i number;
begin
for i in 1..10 loop
if mod(i,2)!=0 then
continue;
end if;
sum:=sum+i;
end loop;
dbms_output.put_line(sum);
end;
/
SYCM-Computer Technology Department, SVCP, Pune Page 23
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
o/p:
30
3)GOTO
goto statement transfers control to a labeled statement within the same block or
subprogram .
Syntax:
goto label_name;
Example:
BEGIN
GOTO second_output;
<<second_output>>
DBMS_OUTPUT.PUT_LINE('We are here!');
END;
/
o/p:
We are here!
o/p
1
2
3
4
6
7
8
9
10
Syntax:
DECLARE
Declaration section
BEGIN
…executable statement;
EXCEPTION
WHEN exception_name THEN
Error handling statements/user defined action to be carried out;
END;
Types of Exception:
1)Predefined Exception
2)User defined exception
Example:
Pl/sql program for Zero_divide exception .
Example.2) using
NO_DATA_FOUND exception
Q)write pl/sql program that retrieves the salary of an employee based on their
emp_id.if the employee id does not exist in the database ,handle the
NO_DATA_FOUND exception and print message saying ”employee id not
found”
o/p
Enter value for n: -6
old 2: n number:=&n;
new 2: n number:=-6;
n is not greater than 1
PL/SQL procedure successfully completed.
Above example will raise exception in else part when user enters value of n less
than 1.
Ans:
DECLARE
c_id customer.id%type := &c_id;
c_name customer.Name%type;
c_addr customer.address%type;
invalid_id EXCEPTION; -- user defined exception
BEGIN
IF c_id <= 0 THEN
RAISE invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr FROM customer WHERE
id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
SYCM-Computer Technology Department, SVCP, Pune Page 30
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
o/p:
Cursor:
A cursor is a temporary work area/context area created in the system memory
when a SQL statement is executed.
In PL/SQL, cursor has the attributes like ,
%FOUND,
%ISOPEN,
%NOTFOUND,
%ROWCOUNT. etc
Implicit Cursor:
Implicit cursors are automatically created by Oracle whenever an SQL statement is
executed, when there is no explicit cursor for the statement.
Whenever a DML statement (INSERT, UPDATE and DELETE) is there, 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.
1 a 25000
2 b 30000
6 c 40000
10 d 30000
SQL> begin
if sql%found then
dbms_output.put_line('table is modified');
else
end if;
end;
table is modified
Explicit cursor:
Explicit cursors are programmer/user 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.
c_dept student.dept%type;
begin
open c1;
loop
fetch c1 into c_rollno,c_name,c_marks,c_dept;
exit when c1%NOTFOUND;
dbms_output.put_line(c_rollno|| ' '||c_name|| ' ' ||c_marks|| ' ' ||c_dept);
end loop;
close c1;
end;
/
o/p
1 ram 90 computer
4 shyam 80 Ej
6 raj 95 IF
3 sam 98 computer
8 rudda 70 Civil
Example 2)
Q. pl/sql program to display record of students in computer department using
/
o/p:
1 ram 90 computer
3 sam 98 computer
Ex. 3) Pl/sql program to display the even number of record (i.e even position
number record) details of student
o/p
4 shyam 80 Ej
3 sam 98 computer
Ex 4. )PL/SQL program that displays the number of items having price more
than 10000
Q. Write step by step syntax to create, open and close cursor in PL/SQL
block.
(Create - 1 Mark, Open - 1 Mark, Close - 1 Mark, Syntax - 1 Mark)
SYCM-Computer Technology Department, SVCP, Pune Page 36
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
Procedure:
A procedure is also called as stored procedure.A procedure is named PL/SQL
block which perform one or more specifies task.
Advantages of Procedure:
1. Security: Procedures offer more security.
2. Productivity: Avoids redundant code for common procedures in multiple
applications.
3. Memory savings: Requires only one copy of the code for multiple users.
4. Performance: Precompiled code hence no compilation is required to execute a
code.
5. Integrity and accuracy: As procedure is needed to be tested only once hence
guarantee of accurate result.
Create procedure:
Syntax:
CREATE OR REPLACE PROCEDURE procedure_name (parameter_name1
mode datatype…parameter_name_n mode datatype)
IS/AS
Declaration section
BEGIN
Execution section
EXCEPTION
exception section
END;
/
mode is IN i.e read mode /OUT i.e write mode /IN and OUT i.e read and write
mode, datatype is the type data.
Compilation:
Show errors;
Execution/run:
Exec procedure_name(parameter_value1,parameter_value2,…);
OR
Execute procedure_name(parameter_value1,parameter_value2,…);
Example of procedure
Pl/sql procedure to Greet user by name.
set serveroutput on;
as
begin
end;
o/p:
Procedure created.
No errors.
as
fact number:=1;
i number;
begin
for i in 1..n
loop
fact:=fact*i;
end loop;
dbms_output.put_line('factorial='||fact);
end;
Procedure created.
No errors.
factorial=24
as
begin
commit;
end;
o/p
exec insert_records;
Delete procedure
Syntax
Definition: Function is a logically grouped set of SQL and Pl/SQL statements that
perform a specific task. function will return value.
Advantages of Function:
1. Code reusability feature can be used.
2. It saves time and cost.
3. Increases flexibility of the program.
4. Memory space required is less.
5. It can return value to the calling program.
Create Function:
Syntax:
CREATE OR REPLACE FUNCTION function_name(parameter_name1 mode
datatype…parameter_name_n mode datatype )
RETURN return_datatype
IS/AS
Declaration_section
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
Example
write pl/sql function to calculate the factorial of gven no.
as
fact number:=1;
i number;
begin
for i in 1..n
loop
fact:=fact*i;
end loop;
return fact;
end;
Function created.
No errors.
SQL> exec:f:=factorial(4);
SQL> print f;
----------
24
Example 2). write pl/sql function which will compute and return the
maximum of two values.
as
begin
if a>b then
return a;
else
return b;
end if;
end;
o/p:
Function created.
SQL> var max number;
SQL> exec:max:=max_fun(14,50);
PL/SQL procedure successfully completed.
SQL> print max;
MAX
----------
50
Example 3) Pass empno as a parameter to function and write a function to
return salary of that
employee.
as
salary number:=50000;
begin
return salary;
end;
Function created.
No errors.
SQL> exec:s:=emp_fun(11);
SQL> print s;
----------
50000
Delete Function
by using drop function we can delete function permenantly.
Syntax:
drop function function_name;
e.g: drop function max_fun;
Trigger:
A trigger is a PL/SQL block structure which is fired when DML statements like
Insert, Delete, Update is executed on a database table. A trigger is triggered
automatically when an associated DML statement is executed.
Trigger is an alternative for the integrity constraint.
:new and :old these two attributes are used in trigger
Types of Triggers:
1. Statement-level trigger
2. Row-level trigger
3. Before-trigger
4. After-trigger
Create Trigger
Syntax
CREATE OR REPLACE TRIGGER trigger name
BEFORE / AFTER
INSERT / UPDATE / DELETE
ON Table_name
FOR EACH ROW/ FOR EACH STATEMENT
WHEN CONDITION
BEGIN
Execution_section
Return return_variable;
EXCEPTION
exception section
Return return_variable;
END;
/
Where,
Example:
create a trigger on emp table which invoked when salary is below 5000(while
insert).
before insert
on emp
begin
if :new.salary<5000 then
end if;
end;
Output:
ERROR at line 1:
11 design 23000
22 development 15000
33 sales 20000
before update
on department
begin
if :new.salary<5000 then
end if;
end;
Trigger created.
ERROR at line 1:
before delete
on emp
begin
if :old.eno<5 then
end if;
end;
o/p
Trigger created.
SYCM-Computer Technology Department, SVCP, Pune Page 50
Unit 4. PL/SQL Programming Ms.S.A.Kshirsagar
ERROR at line 1:
Advantages of triggers:
end if;
end;
/
Or using nested if
declare
a number:=&a;
b number:=&b;
c number:=&c;
begin
if(a>b) then
if(a>c) then
dbms_output.put_line(‘a is greater’);
else
dbms_output.put_line(‘c is greater’);
else if(b>c)
dbms_output.put_line(‘b is greater’)
else
dbms_utput.put_line(‘c is greater’)
end if;
end if;
end if;
end;
/
q.write pl/sql program to reverse a number (e.g if number is 123 the reverse
of it is 321)
ans:
declare
n number:=&n;
rev number:=0;
rem number:=0;
begin
while(n>0)
loop
rem=mod(n,10);
rev:=rev*10+rem;
n:=n/10;
end loop;
dbms_output.put_line(rev);
end;
/
Q. Write Pl/SQL program to handle zero_divide exception.
declare
a number:=20;
b number:=0;
c number;
begin
dbms_output.put_line(a);
dbms_output.put_line(b);
c:= a / b; --raise exception
dbms_output.put_line(c); -- result will not displayed due to exception is raised
implicitly as b is 0
exception
when zero_divide then
dbms_output.put_line(‘trying to divide by zero ‘);
end;
/
delete trigger.
Write and Explain the syntax for creating database trigger. W-22 4M
Explain trigger with suitable example S-23 4M
Define database trigger. How to create and delete trigger ? W-19 4M
Write and explain syntax for creating Trigger. S-22 4M
Write a PL/SQL program to calculate factorial of a given number. S-19 6M
State any two advantages of functions in PL/SQL. W-19 2M
Explain any one control structure in PL/SQL with example. w-19 4M
Explain conditional control in PL/SQL with example. S-22 4M
Write a PL/SQL program to print n even numbers using For Loop. W-19 6M
Draw the block structure of PL/SQL . List advantages of PL/SQL. W-18 4M
Write a PL/SQL program which accept the customer ID from the user if user enters W-18 6M
an invalid ID then the exception invalid_id is raised using exception handling(
List two advantages of PL/SQL. S-22 2M
Write a PL/SQL program, which accept the number from user. If user enters an odd S-22 6M
number then exception invalid number is raised using user defined exception
handling
Differentiate between PL/SQL procedure and function with syntax and example. S-24 6M
Write PL/SQL program to print number of employee working in specified S-24 4M
department consider emp table and accept dept-no. from user
Write PL/SQL code to print largest number from three numbers. S-24 4M
Write a PLISQL code to print reverse of a number. W-22 4M
Write a trigger which invokes on deletion of record on emp table. W-22 4M
Write a PLISQL code to check whether specified employee is present in Emp table W-22 6M
or not. Accept empno from user. If employee does not exist display message using
exception handling.
State syntax of while loop command. S-23 2M
Write a PL-SQL program to print odd numbers from 1 to 10. S-23 4M
Explain for loop syntax in PL-SQL with example of printing 10 to 1 reverse S-23 6M
numbers.
Explain function in PL-SQL with suitable example S-23 6M
Explain function in PL/SQL with example. W-18 4M
Explain procedures in PL/SQL with example. W-23 4M
Compare database triggers and procedures. (Write four differences) And explain W-23 4M
the use of database trigger
Write a PL/SQL program to print sum of n odd numbers using for loop. W-23 6M