Unit4-PLSQL - Programming in DBMS
Unit4-PLSQL - Programming in DBMS
Exception Handling: Exception is nothing but an error. Exception can be raise when DBMS
encounters errors or it can be raised explicitly. When the system throws a warning or has an
error it can lead to an exception. Such exception needs to be handled and can be defined
internally or user defined. Exception handling is nothing but a code block in memory that will
attempt to resolve current error condition.
Syntax:
DECLARE
; Declaration section
…executable statement;
EXCEPTION
WHEN ex_name1 THEN
END; DECLARE
s_rollNostudents.rollNo%type :=
10; s_namestudents.name%type;
s_addressstudents.address%type;
BEGIN
SELECT rollNo, name, address FROM students WHERE rollNo =
s_rollNo; dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' ||
s_address);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such
student!'); WHEN others THEN
dbms_output.put_line('Error!');
END;
Q. Write a PL/SQL program to print numbers from 50 to 60 using for loop. 4 Marks
(Note: Any other Logic also considered)
DECLARE
x number
:=50; BEGIN
LOOP
dbms_output.
put_line(x); x
:= x +1;
IF x >60 THEN
exit; END
IF; END
LOOP;
END;
Example:
CREATE OR REPLACE TRIGGER trg1
BEFORE INSERT ON EMP
FOR EACH ROW
BEGIN
IF :new.sal<=0 THEN
Rasie_application_error(„Salary should be greater than 0‟);
END IF;
END;
Example :
DECLARE
p VARCHAR2(30);
n PLS_INTEGER := 37;
BEGIN
FOR j in 2..ROUND(SQRT(n)) LOOP
IF n MOD j = 0 THEN
p := ' is not a prime number';
GOTO print_now;
END IF;
END LOOP;
p := ' is a prime number';
<<print_now>>
DBMS_OUTPUT.PUT_LINE(TO_CHAR(n) || p);
END;
Q.Explain PL/SQL block structure. 4 Marks
Block structure of PL/SQL:
Declare
Declaration of memory variables
BEGIN (Mandatory)
SQL executable statements
Exception Handling
errors END;
(Mandatory)
A block begins with a declarative section where variables are declared. This is followed by a
section containing the procedural statements surrounded by BEGIN and END keywords. Each
block must have Begin and End statements and may optionally include an exception section to
handle errors. End section marks the end of PLSQL block.
It must be declare by the user in the declaration part of the block where the exception is used. It is
raised explicitly in sequence of statements using: Raise_application_error (error_no,
error_name);
Q. Write a PL/SQL program using while loop to display n even numbers. 4 Marks
(Correct logic - 2 marks; correct syntax - 2 marks) [** Note: Any relevant logic can be
considered**]
SET SERVEROUTPUT ON;
DECLARE n number:= &n;
i number:= 0;
cnt number:=0;
BEGIN
WHILE (cnt< n) LOOP
if( mod (i,2)=0) then
Dbms_output.put_line(i);
cnt:=cnt+1;
End if;
i:=i+1;
END LOOP;
END;
1. Declare
2. Begin
3. End
4. Exception
5. dbms_output.put_line();
6. If condition then
Statements Else Statements End if;
7. LOOP
<loop_body>
EXIT WHEN (condition); END LOOP;
9. WHILE <condition> LOOP
Database Trigger: Database trigger are ‗event-condition-action model„ which are fixed on certain
event. Trigger represents action to be taken if some event happens. In case of DBMS, triggers are
automatically fired when tables are modified with insert, update and delete etc.
Comparison:
Database Trigger Procedures
1. Triggers are fired when particular SQL 1. Procedures are executed when they are
commands (DML) are executed Called
2. Triggers have events and related actions 2. Procedure do not have events and related
Actions
3. Triggers are called implicitly 3. Procedure are called explicitly
1. The Declaration section : Declaration of memory variables used later in begin section.
2. The Begin..End section : SQL executable statements for manipulating table data should be in
BEGIN....END block.
3. The Exception section : SQL and/or PL-SQL code to handle errors that may crop up during
execution of the above code block.
Q. List types of cursor and explain each with example. 4 Marks
(Description - 1 mark; example - 1 mark for each type; 1 mark shall be awarded if only list is
given) [**Note: any other examples showing use of implicit and explicit cursor can be
considered**]
Types of Cursor
Implicit cursor
Explicit cursor
Implicit cursor: If database engine opens a cursor for internal processing, it is called as implicit
cursor. Example of implicit cursor:
Declare
Begin
Update emp set salary= salary +500 where empno =&empno;
If SQL%FOUND then
Dbms_out.put_line(―Emp table modified‖);
Else Dbms_out.put_line(―Emp table modified‖);
End if;
End;
Explicit cursor: A user can open a cursor for processing data as required. Such user defined cursors
are known as explicit cursors.
Example of explicit cursor:
Declare
Cursor c1 is select empno, salary from emp Where deptno=10;
Ecode emp.empno%Type;
Sal emp.salary%Type;
Begin
Open c1;
If c1%ISOPEN then
Loop
Fetch c1 into ecode,sal;
If c1% NOTFOUND then
Exit;
End if;
Update emp set salary = salary+500;
End Loop;
Close c1;
Else
Dbms_out.put_line(―unable to open‖);
End if;
End;
WINTER 2016
Syntax:
DECLARE
; Declaration section
…executable statement;
EXCEPTION
WHEN ex_name1 THEN
; Error handling statements/user defined action to be carried out;
END;
Types of Exception:
1) Predefined Exception/system defined exception/named exception:
Are always automatically raised whenever related error occurs. The most common
errors that can occur during the execution of PL/SQL. Not declared explicitly i.e.
cursor already open, invalid cursor, no data found, zero divide and too many rows
etc. Programs are handled by system defined Exceptions.
Q. Write a PL/SQL program to print even or odd number from given range (Accept
number range from user). 4 Marks
{**NOTE: any relevant program logic shall be considered**}
DECLARE
A NUMBER :=&A;
B NUMBER :=&B;
C NUMBER :=&C;
BEGIN
IF(C=1) THEN
FOR I IN A..B LOOP
IF(MOD(I,2)=0) THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
ELSE
FOR I IN A..B LOOP
IF(MOD(I,2)=1) THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END IF;
END;
OR
-- PL/SQL code to display even numbers
DECLARE
A NUMBER :=&A;
B NUMBER :=&B;
BEGIN
FOR I IN A..B LOOP
IF(MOD(I,2)=0) THEN
DBMS_OUTPUT.PUT_LINE(I);
END IF;
END LOOP;
END;
WHILE: If it is not known in advance how many times a sequence of statements needs
to execute. In such cases, one should use PL/SQL WHILE LOOP statement.
Syntax:
WHILE condition LOOP
sequence_of_statements;
END LOOP;
Example:
i number := 1;
while (i<=10) Loop
dbms_output.put_line(i);
i :=i+1;
End Loop;
Advantages of triggers:
1. Triggers provide an alternative way to check the integrity of data.
2. Can catch errors in business logic in the database layer.
3. SQL triggers provide an alternative way to run scheduled tasks.
4. Triggers are very useful to audit the changes of data in tables.
2. Nested If:
• In this, any number of ELSIF clauses can be used with one IF statement.
• Either set of actions of the result of the first IF statement of ELSE statement can
contain further IF statements before specific actions are performed.
• Each nested IF statement must terminate with a corresponding END IF.
• Syntax:
If condition then
Statements
If condition then
Statements
Else
If condition then
Statements
Else condition then
Statements
End if;
End if;
End if;
3. Case
• Evaluates a list of conditions and returns one of multiple possible result
expressions.
• CASE can be used in any statement or clause that allows a valid expression. For
example, you can use CASE in statements such as SELECT, UPDATE, DELETE
and SET, and in clauses such as select_list, IN, WHERE, ORDER BY, and
HAVING.
• Synatx:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END
Iterative Control:
1. Simple Loop
2. While Loop
3. For Loop
1. Simple Loop
LOOP statements let you execute a sequence of statement multiple times.
Place the keyword LOOP before the first statement in the sequence and the
keyword END LOOP after the last statement in the sequence.
Syntax:
Endless loop
LOOP
<loop_body>
END LOOP;
Conditional loop
LOOP
<loop_body>
EXIT WHEN (Condition);
END LOOP;
The EXIT WHEN statement lets you complete a loop if further processing is impossible
or undesirable.
When the EXIT statement encountered, the condition in the WHEN clause is evaluated.
If the condition is true, the loop completes and control passes to the next statement.
2. While Loop
The WHILE LOOP statement associates a condition with a sequence of statements.
Before each iteration of loop, the condition is evaluated.
If the condition is true, the sequence of statement is executed, then control resumes at the
top of the loop.
If the condition is false or null, the loop is bypassed and control passes to the next
statement.
Syntax:
WHILE <Condition> LOOP
<loop body>
END LOOP;
3. For Loop :
The FOR LOOP statement specifies a range of integers, then execute a sequence of
statements once for each integer in the range.
To reverse the range , “REVERSE” keyword is used.
The syntax is :
FOR i IN 1..N LOOP
<loop_body>
END LOOP;
4. Sequential Control:
Label can be used to give a label or name to the piece of code. And once the name is
given to it, user can call that piece of code with that label whenever and wherever
required in the program .
Syntax for label is as follows:
<<label_name>>
Statements;
The Goto statement is used to transfer the control or to change the sequence of the
instructions.
Syntax for goto statement is as follows:
Goto<<label_name>>
WINTER 2015
Q. What statement is used in PL/SQL to display the output?
(Correct statement – 2 Marks)
dbms_output.put_line( var/msg);
OR
set serveroutput on;
dbms_output.put_line( var/msg);
Q. What is Cursor?
(Cursor Description – 2 Marks)
Oracle creates a memory area, known as context area, for processing an SQL
statement, which
contains all information needed for processing the statement, for example, number of
rows processed, etc.
Q. Write PL/SQL program to print even or odd numbers from given range. (Accept
number
from user.)
(Correct logic - 2 Marks, correct syntax – 2 Marks)
[** Note: Any relevant logic can be considered]
Logic 1 :
Declare
n1 number := &n1;
n2 number :=&n2;
i number ;
begin
dbms_output.put_line(‘Even numbers are :’);
for i in n1..n2
loop
if mod(i,2)=0 then
dbms_output.put_line(i);
end if;
end loop;
dbms_output.put_line(‘Odd numbers are :’);
for i in n1..n2
loop
if mod(i,2)!=0 then
dbms_output.put_line(i);
end if;
end loop;
end;
Logic 2 :
Declare
n1 number := &n1;
n2 number :=&n2;
i number ;
begin
for i in n1..n2
loop
if mod(i,2)=0 then
dbms_output.put_line(‘Even :’ || i);
else
dbms_output.put_line(‘Odd :’ || i);
end if; end
loop; end;
2. Case
Evaluates a list of conditions and returns one of multiple possible result expressions.
CASE can be used in any statement or clause that allows a valid expression
Syntax:
CASE [ expression ]
WHEN condition_1 THEN result_1
WHEN condition_2 THEN result_2
...
WHEN condition_n THEN result_n
ELSE result
END CASE;
Q. Write PL/SQL program to display factorial of any number.
(Correct logic – 2 Marks, correct syntax – 2 Marks)
[**Note: Any other relevant logic can be considered]
declare
f number :=1;
n number := &n;
begin
for i in 1..n
loop
f := f * i; end loop;
dbms_output.put_line(f);
end;
/
Example
Cursor display employee information from emp_information table whose emp_no is
four
(4).
DECLAR
E
cursor c(no number) is select * from
emp_information where emp_no = no;
tmp
emp_information%rowtype;
BEGIN
OPEN c(4);
FOR tmp IN c(4) LOOP
dbms_output.put_line('EMP_No: '||tmp.emp_no);
dbms_output.put_line('EMP_Name:
I|tmp.emp_name); dbms_output.put_line('EMP_Dept:
'||tmp.emp_dept);
dbms_output.put_line('EMP_Salary:'||tmp.emp_salar);
END Loop;
CLOSE ;
END;
/