SlideShare a Scribd company logo
1 of 36
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.
Types of Exceptions
• 1 System-defined exceptions
• 2 User-defined exceptions
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.
The following table lists few of the
important pre-defined exceptions:
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;
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;
•
Out put
Enter value for num1: 4
Enter value for num2: 0
Zero divide error
• PL/SQL procedure successfully completed.
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;
Note that
Predefined exception automatically raised
by oracle when error situation occurs.
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.
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;
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.
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
• The following Example- shows error if user enters empid less than=0;
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;
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;
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;
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.
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
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.
Functions
• Definition: Function is a named PL/SQL block that perform a
specific task, Function must returns value.
Syntax to create Function
Create or replace procedure function_name(var1 In
datatype,……… )
return type
As
-----
----
Begin
Executable Statements;
end;
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.
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
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;
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;
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
Exexecute 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
Exselect fun_name(values) from dual;
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
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
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
• 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
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
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> /
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.
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
LOCKS

More Related Content

What's hot

Control structure C++
Control structure C++Control structure C++
Control structure C++Anil Kumar
 
Star pattern programs in java Print Star pattern in java and print triangle ...
Star pattern programs in java Print Star pattern in java and  print triangle ...Star pattern programs in java Print Star pattern in java and  print triangle ...
Star pattern programs in java Print Star pattern in java and print triangle ...Hiraniahmad
 
Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automationPositive Hack Days
 
Linq & lambda overview C#.net
Linq & lambda overview C#.netLinq & lambda overview C#.net
Linq & lambda overview C#.netDhairya Joshi
 
Reactive computing
Reactive computingReactive computing
Reactive computingStan Lea
 
Oracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurOracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurIndiaOptions Softwares
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sqlÑirmal Tatiwal
 
SQL Tuning02-Intorduction to the CBO Optimizer
SQL Tuning02-Intorduction to the CBO OptimizerSQL Tuning02-Intorduction to the CBO Optimizer
SQL Tuning02-Intorduction to the CBO OptimizerZhaoyang Wang
 

What's hot (13)

Control structure C++
Control structure C++Control structure C++
Control structure C++
 
Oracle: Control Structures
Oracle: Control StructuresOracle: Control Structures
Oracle: Control Structures
 
Star pattern programs in java Print Star pattern in java and print triangle ...
Star pattern programs in java Print Star pattern in java and  print triangle ...Star pattern programs in java Print Star pattern in java and  print triangle ...
Star pattern programs in java Print Star pattern in java and print triangle ...
 
Reverse Engineering automation
Reverse Engineering automationReverse Engineering automation
Reverse Engineering automation
 
Linq & lambda overview C#.net
Linq & lambda overview C#.netLinq & lambda overview C#.net
Linq & lambda overview C#.net
 
Reactive computing
Reactive computingReactive computing
Reactive computing
 
User Defined Functions
User Defined FunctionsUser Defined Functions
User Defined Functions
 
Handling
HandlingHandling
Handling
 
Oracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |ThrissurOracle Training in Kochi | Trivandrum |Thrissur
Oracle Training in Kochi | Trivandrum |Thrissur
 
Procedure and Functions in pl/sql
Procedure and Functions in pl/sqlProcedure and Functions in pl/sql
Procedure and Functions in pl/sql
 
Basic c++
Basic c++Basic c++
Basic c++
 
SQL Tuning02-Intorduction to the CBO Optimizer
SQL Tuning02-Intorduction to the CBO OptimizerSQL Tuning02-Intorduction to the CBO Optimizer
SQL Tuning02-Intorduction to the CBO Optimizer
 
Cursors in MySQL
Cursors in MySQL Cursors in MySQL
Cursors in MySQL
 

Similar to Exceptions Triggers function in SQL by Vasant Bhabad

Similar to Exceptions Triggers function in SQL by Vasant Bhabad (20)

SQL / PL
SQL / PLSQL / PL
SQL / PL
 
ORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERSORACLE PL SQL FOR BEGINNERS
ORACLE PL SQL FOR BEGINNERS
 
04 Handling Exceptions
04 Handling Exceptions04 Handling Exceptions
04 Handling Exceptions
 
Triggers n Cursors.ppt
Triggers n Cursors.pptTriggers n Cursors.ppt
Triggers n Cursors.ppt
 
PLSQL Tutorial
PLSQL TutorialPLSQL Tutorial
PLSQL Tutorial
 
Oracle pl sql
Oracle pl sqlOracle pl sql
Oracle pl sql
 
Oracle - Program with PL/SQL - Lession 08
Oracle - Program with PL/SQL - Lession 08Oracle - Program with PL/SQL - Lession 08
Oracle - Program with PL/SQL - Lession 08
 
PL-SQL.pdf
PL-SQL.pdfPL-SQL.pdf
PL-SQL.pdf
 
Programming in Oracle with PL/SQL
Programming in Oracle with PL/SQLProgramming in Oracle with PL/SQL
Programming in Oracle with PL/SQL
 
Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16Oracle - Program with PL/SQL - Lession 16
Oracle - Program with PL/SQL - Lession 16
 
Oaktable World 2014 Toon Koppelaars: database constraints polite excuse
Oaktable World 2014 Toon Koppelaars: database constraints polite excuseOaktable World 2014 Toon Koppelaars: database constraints polite excuse
Oaktable World 2014 Toon Koppelaars: database constraints polite excuse
 
10 Creating Triggers
10 Creating Triggers10 Creating Triggers
10 Creating Triggers
 
PL/SQL Fundamentals I
PL/SQL Fundamentals IPL/SQL Fundamentals I
PL/SQL Fundamentals I
 
Oracle: Cursors
Oracle: CursorsOracle: Cursors
Oracle: Cursors
 
Oracle:Cursors
Oracle:CursorsOracle:Cursors
Oracle:Cursors
 
PLSQL.pptx
PLSQL.pptxPLSQL.pptx
PLSQL.pptx
 
Introduction to mysql part 3
Introduction to mysql part 3Introduction to mysql part 3
Introduction to mysql part 3
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
Stored procedure
Stored procedureStored procedure
Stored procedure
 
L9 l10 server side programming
L9 l10  server side programmingL9 l10  server side programming
L9 l10 server side programming
 

Recently uploaded

AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptNishitharanjan Rout
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17Celine George
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfPondicherry University
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - Englishneillewis46
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptxJoelynRubio1
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsSandeep D Chaudhary
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Jisc
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxCeline George
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and ModificationsMJDuyan
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...Nguyen Thanh Tu Collection
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxPooja Bhuva
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSCeline George
 

Recently uploaded (20)

AIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.pptAIM of Education-Teachers Training-2024.ppt
AIM of Education-Teachers Training-2024.ppt
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17How to Create and Manage Wizard in Odoo 17
How to Create and Manage Wizard in Odoo 17
 
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdfFICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
FICTIONAL SALESMAN/SALESMAN SNSW 2024.pdf
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
Graduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - EnglishGraduate Outcomes Presentation Slides - English
Graduate Outcomes Presentation Slides - English
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
OSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & SystemsOSCM Unit 2_Operations Processes & Systems
OSCM Unit 2_Operations Processes & Systems
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 
How to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptxHow to setup Pycharm environment for Odoo 17.pptx
How to setup Pycharm environment for Odoo 17.pptx
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
Our Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdfOur Environment Class 10 Science Notes pdf
Our Environment Class 10 Science Notes pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Interdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptxInterdisciplinary_Insights_Data_Collection_Methods.pptx
Interdisciplinary_Insights_Data_Collection_Methods.pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 

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.
  • 2. Types of Exceptions • 1 System-defined exceptions • 2 User-defined exceptions
  • 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.
  • 4. The following table lists few of the important pre-defined exceptions:
  • 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;
  • 9. Note that Predefined exception automatically raised by oracle when error situation occurs.
  • 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.
  • 21. Functions • Definition: Function is a named PL/SQL block that perform a specific task, Function must returns value.
  • 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 Exexecute 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 Exselect 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
  • 36. LOCKS