Exceptions Triggers function in SQL by Vasant Bhabad
1. Exceptions
An error condition during a program execution is called an
exception in PL/SQL.
PL/SQL supports programmers to catch such conditions using EXCEPTION block
in the program and an appropriate action is taken against the error condition.
3. Pre-defined Exceptions
System exceptions are automatically raised by Oracle, when a
program violates a RDBMS rule.
There are some system exceptions which are raised automatically
whenever error situation occurs.
5. Structure of Exception Handling.
DECLARE
--Declaration section
BEGIN
-- executable statements
EXCEPTION
WHEN ex_name1 THEN
--Error handling statements
WHEN ex_name2 THEN
--Error handling statements
WHEN Others THEN
--Error handling statements
END;
6. Example of ZERO_DIVIDE exception• SQL> declare
• 2 num1 int;
• 3 num2 int;
• 4 div number(4);
• 5 begin
• 6 num1:=&num1;
• 7 num2:=&num2;
• 8 div:=num1/num2;
• 9 dbms_output.put_line('Division='||div);
• 10 exception
• 11 when zero_divide
• 12 then
• 13 dbms_output.put_line('Zero divide error');
• 14 end;
•
7. Out put
Enter value for num1: 4
Enter value for num2: 0
Zero divide error
• PL/SQL procedure successfully completed.
8. No_DATA_FOUND
• 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;
10. 2)User-Defined Exception
• 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(Exception_Number,Error_Message);
• • The Error number must be between -20000 and -20999
• The Error_message is the message you want to display when the error
occurs.
11. User Defined Exceptions
• PL/SQL allows you to define your own exceptions according to the
need of your program. A user-defined exception must be declared
and then raised explicitly
The syntax for declaring an exception is −
DECLARE
my-exception EXCEPTION;
12. Example
The following example illustrates the concept.
This program asks for a customer ID, when the
user enters an invalid ID, the exception
invalid_id is raised.
13. Structure of Exception handling
• Declare
exceptionname1 exception;
exceptionname2 exception;
----
---
Begin
---
---
If(cond) then raise exceptionname1;
ElsIf(cond) then raise exceptionname2;
End if;
Exception
When exceptionname1 then
------
When exceptionname2 then
Statements;
end
14. • The following Example- shows error if user enters empid less than=0;
15. SQL> declare
2 invalid_id exception;
3 salary number(9);
4 eid number(4);
5 begin
6 eid:=&eid;
7 if(eid<=0) then
8 raise invalid_id;
9 else
10 select sal into salary from emp where empno=eid;
11 dbms_output.put_line('salary='||salary);
12 end if;
13 exception
14 when invalid_id
15 then
16 raise_application_error(-20001,'Invalid Id');
17 end;
18 .
SQL> /
Enter value for eid: 7369
old 6: eid:=&eid;
new 6: eid:=7369;
16. Procedures
• Definition: A procedure is named PL/SQL block which perform one or more specifies
task
• Syntax to create Procedure-
Create or replace procedure procedure_name(var1 In/OUT datatype,….,)
As
----
Begin
Executable Statements;
end;
17. Example
• The following example creates a simple procedure that displays the
string 'Hello World!' on the screen when executed.
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
18. Example- Procedure to find out area of
circle
create or replace procedure p1(rad number, area out number)
as
pi number:=3.14;
begin
area:=pi*rad*rad;
end;
SQL> /
Procedure created.
19. Write PL/SQL procedure to calculate
factorial of a give number.
create or replace procedure Factorial(n in number)
is
v number :=1;
begin
for i in 1..n
loop
v :=v * i;
end loop;
dbms_output.put_line(v);
end;
Procedure created
20. output
• SQL> Begin
• Factorial(5);
• End;
•
SQL> /
120
• Or procedure can be called using execute keyword as below
SQL> execute factorial(5);
120
PL/SQL procedure successfully completed.
22. Syntax to create Function
Create or replace procedure function_name(var1 In
datatype,……… )
return type
As
-----
----
Begin
Executable Statements;
end;
23. Example on Function
Functions for ADDITION of TWO Numbers
create or replace function f1(a int,b int)
return int
is
x int;
begin
x:=a+b;
return x;
end;
• SQL> /
• Function created.
24. Functions To Find AREA of Circle
SQL> create function Aole (rad number) return int
2 as
3 pi number:=3.14;
4 A number;
5 begin
6 A:=pi*rad*rad;
7 return A;
8 end;
9 .
SQL> /
Function created.
SQL> select Aole(3) from dual;
AOLE(3)
----------
28
25. Write a function to find factorial of number.
• Create function or replace factno(num1 number) return int
Is
F number:=1;
I number:=1;
Begin
While(I<=num1) loop
F:=F*I;
I:=I+1;
End loop;
Return f;
End;
26. Calling Function
• Function can be called using Select Statement
• Select factno(6) from dual;
• Dropping Function
Syntax- Drop function fun_name;
Ex- drop function factno;
27. Difference Between Functions and Procedure
• 1)Function always returns Value
• 2) Call using Simple select Statement
3)Function mainly used for complex
calcualtions
ex- to Find factorial of a number.
4)Syntax to create procedure
Create or replace procedure
proc_name(var1 type,…)
Is
Begin
PL/SQL block
5)Procedure executed using execute
statement
Exexecute proc_name;
• 1)May or May not returns value
• 2)Called using Exceute procedurename;
• 3)mainly used for business logic
ex- Updation of salary.
4)Syntax to create Function
Create or replace function fun_name(var1
type,…) return type
Is
Begin
PL/SQL block
5)Function Called using select statement
Exselect fun_name(values) from dual;
28. Data base Triggers
• Defn- A database trigger is PL/SQL program associated
with a specific database table. Triggers executes
(fires) automatically when a given SQL
operation (like INSERT, UPDATE or DELETE)
affects the table.
• Unlike a procedure, or a function, which must be
invoked explicitly, database triggers are invoked
implicitly
29. Database triggers can be used to perform
any of the following/Advatages:
• Audit data modification
• Maintains Integrity
• Derive column values automatically
• Provides security
• Maintain replicate tables
• Enforce complex business rules
30. Syntax To Create Trigger
CREATE [OR REPLACE] TRIGGER trigger_name
{BEFORE|AFTER/INSTEAD OF} --Trigger Timing
INSERT/UPDATE/DELETE -- Triggering Event
ON table_name
[FOR EACH ROW/For each statement] --Trigger Type
Pl/SQL Block
31. • Trigger_name name of trigger
• Trigger_Timing Time when trigger Fires
• Triggering Event any DML operation
(i.e INSERT/DELETE/UPDATE)
• Trigger Type event affects on for each row or for
each statement
32. Types of Trigger
1)Before
2)After
3)Instead oF
• 1)Before
Trigger f i r e s b e f o r e the triggering event occurs in table.
2)After
Trigger f i r e s a f t e r the triggering event occurs in table .
3)Instead oF
Instead of t r i g g e r s a r e b a s e d o n V i e w s
33. Example on trigger
Following deleted_emp trigger maintains record of staff who retires
from job
SQL> create or replace trigger deleted_emp
2 after delete
3 on emp
4 for each row
5 begin
6 insert into backup_emp(empno,ename,deptno,sal,job)
7 values(:old.empno,:old.ename,:old.deptno,:old.sal,:old.job);
8 end;
9 .
SQL> /
34. Here we have to first create table
backup_emp as below
• SQL> create table backup_emp(empno number(4),ename varchar(16),deptno
number(2),sal number(8),job varchar(15));
Then trigger fires automatically after delete command
SQL> delete from emp;
11 rows deleted.
35. If we check in backup_emp table we can get
deleted data from this table.
• SQL> select * from backup_emp;
• EMPNO ENAME DEPTNO SAL JOB
• ---------- ---------------- ---------- ---------- ---------------
• 7369 Raj 20 800 Clerk
• 7499 Sachin 30 16000 Salesman
• 7521 Ajay 30 12500 Salesman
• 7934 Abrahham 10 13000 Clerk
• 7902 Julie 20 30000 Analyst
• 7900 Kalim 30 9500 Clerk
• 7876 Rahul 20 11000 Clerk
• 7844 Shammim 30 15000 Saleman
• 7839 Rakesh 10 50000 President
• 7788 Apurva 20 30000 Analyst
• 7782 Savita 10 24500 Manager