0% found this document useful (0 votes)
168 views80 pages

PL-SQL - Part2: Exception Handling Procedure Function Cursors Trigger

This document discusses various PL/SQL programming concepts including exception handling, procedures, functions, cursors, and triggers. It provides examples of using exception handling blocks to catch errors, defines procedures and functions, and describes implicit and explicit cursors. Procedures and functions can accept parameters using IN, OUT, or INOUT modes. Explicit cursors are used to fetch multiple rows from a SELECT statement one row at a time into variables or records.

Uploaded by

KARTIKAY LADDHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
168 views80 pages

PL-SQL - Part2: Exception Handling Procedure Function Cursors Trigger

This document discusses various PL/SQL programming concepts including exception handling, procedures, functions, cursors, and triggers. It provides examples of using exception handling blocks to catch errors, defines procedures and functions, and describes implicit and explicit cursors. Procedures and functions can accept parameters using IN, OUT, or INOUT modes. Explicit cursors are used to fetch multiple rows from a SELECT statement one row at a time into variables or records.

Uploaded by

KARTIKAY LADDHA
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 80

PL-SQL –PART2

• Exception Handling
• Procedure
• Function
• Cursors
• Trigger
Exception handling

 An exception is an error condition during a program


execution. PL/SQL supports programmers to catch such
conditions using EXCEPTION block in the program and an
appropriate action is taken against the error condition.
 There are 3 types of Exceptions
a) Named System Exceptions or Predefined exception
b) Unnamed System Exceptions or Internally defined
exception
c) User-defined Exceptions
Exception Message Part

 When an exception occurs a messages which explains its


cause is received.
PL/SQL Exception message consists of three parts.
1) Type of Exception
2) An Error Code
3) A message

Note: Handling the exceptions we can ensure a PL/SQL block


does not exit abruptly.
Structure of Exception Handling
General Syntax for coding the exception section
 DECLARE
 Declaration section
 BEGIN
 Exception section
 EXCEPTION
 WHEN ex_name1 THEN
 -Error handling statements
 WHEN ex_name2 THEN
 -Error handling statements
 WHEN Others THEN
 -Error handling statements
 END;
Named System Exceptions

 System exceptions are automatically raised by Oracle, when a


program violates a RDBMS rule.
 There are some system exceptions which are raised
frequently, so they are pre-defined and given a name in Oracle
which are known as Named System Exceptions.
 For example: NO_DATA_FOUND and ZERO_DIVIDE are
called Named System exceptions.
Named system

 Named system exceptions are:


1) Not Declared explicitly,
2) Raised implicitly when a predefined Oracle error occurs,
3) caught by referencing the standard name within an
exception-handling routine.
Example of exception handling
PL/SQL Exception Handling(Named exception)
Divide by zero exception

 Declare
 v_num1 number(6):=5;
 v_num2 number(6):=0;
 Begin
 v_num1:= v_num1 / v_num2;
 DBMS_OUTPUT.PUT_LINE(‘Answer is ‘|| v_num1 );
 EXCEPTION
 WHEN ZERO-DIVIDE Then
 dbms_output.put_line(‘Error occurred due to divide by zero ‘);
 END;
TOO Many rows exception
DECLARE
v_lname VARCHAR2 (15);
BEGIN
SELECT last_name INTO v_lname
FROM employees
WHERE first_name = 'John';
DBMS_OUTPUT.PUT_LINE ('Last name is :' || v_lname);
EXCEPTION
WHEN TOO_MANY_ROWS THEN
DBMS_OUTPUT.PUT_LINE (' Your SELECT statement retrieved multiple
rows. Consider using a cursor.');
END;
/

Output:
Your SELECT statement retrieved multiple rows. Consider using a cursor.
PL/SQL procedure successfully completed.
TOO Many rows exception
 declare
cursor c1 is select * from emp;
r emp%rowtype;
begin
open c1;
dbms_output.put_line('display employee''s name and number');
loop
fetch c1 into r;
exit when c1%notfound;
dbms_output.put_line(r.empno||' '||r.ename);
end loop;
dbms_output.put_line('update employee salary');
open c1;
 exception
 when cursor_already_open then
          dbms_output.put_line('cursor must be closed before reopening it');
 end;

Tags:ORACLE CURSOR_ALREADY_OPEN EXCEPTION HANDLING,Handling CURSOR_ALREADY_OPEN Exception in PL/SQL, ORA-
06511: PL/SQL: cursor already open,
Invalid Cursor
 declare
cursor c1 is select sal  from emp;
vsal emp.sal%type;
begin
loop
fetch c1 into vsal;
exit when c1%notfound;
dbms_output.put_line(vsal);
end loop;
dbms_output.put_line('Processed records:-'||c1%rowcount);
close c1;
end;
/

ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 6
Invalid Cursor
 declare
cursor c1 is select sal  from emp;
vsal emp.sal%type;
begin
loop
fetch c1 into vsal;
exit when c1%notfound;
dbms_output.put_line(vsal);
end loop;
dbms_output.put_line('Processed records:-'||c1%rowcount);
close c1;
exception
when invalid_cursor then
dbms_output.put_line('Cursor is not handled properly');
end;
/
Output

Cursor is not handled properly ,ORA-10001PL/SQL: cursor is invalid


unNamed or Internally Defined
Exception
 Oracle have internally Defined exceptions, which are in form of ORA-n , where –
n is negative number
 Internally defined exceptions generally do not have any names, also they are
raised by oracle implicity .
Declare
count integer;
Begin
count:=9999999999; --overflow;
End;
Output is
ORA-01426 : numeric overflow
Raising Exceptions

 Exceptions can be raised explicitly by the programmer by using the command RAISE.


Following is the simple syntax for raising an exception
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition
THEN
RAISE exception_name;
END IF;
EXCEPTION WHEN exception_name
THEN statement;
END;
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, using either a RAISE statement or the
procedure DBMS_STANDARD.RAISE_APPLICATION_ERRO
R.
PL/SQL stored procedure

 The PL/SQL stored procedure or simply a procedure is a


PL/SQL block which performs one or more specific tasks. It is
just like procedures in other programming languages.

The procedure contains a header and a body.


 Header: The header contains the name of the procedure and the
parameters or variables passed to the procedure.
 Body: The body contains a declaration section, execution section
and exception section similar to a general PL/SQL block.
PL/SQL Create Procedure
Executing a Standalone Procedure

A standalone procedure can be called in two ways


 Using the EXECUTE  or EXEC keyword
 Calling the name of the procedure from a PL/SQL block
 The above procedure named 'greetings' can be called with the
EXECUTE keyword as −
 EXECUTE greetings;
 Output :
The above call will display −
Hello World PL/SQL procedure successfully completed.
How to pass parameters in procedure

There is three ways to pass parameters in procedure:


 IN parameters: The IN parameter can be referenced by the
procedure or function. The value of the parameter cannot be
overwritten by the procedure or the function.
 OUT parameters: The OUT parameter cannot be referenced by the
procedure or function, but the value of the parameter can be
overwritten by the procedure or function.
 INOUT parameters: The INOUT parameter can be referenced by
the procedure or function and the value of the parameter can be
overwritten by the procedure or function.
IN-OUT Parameter
IN &OUT Mode
PL/SQL Function
Another PL/SQL Function Example
Calling PL/SQL Function
PL/SQL Recursive Function
Cursor

 A cursor is a temporary work area created in the system


memory when a SQL statement is executed
 A cursor contains information on a select statement and the
rows of data accessed by it.
 This temporary work area is used to store the data retrieved
from the database, and manipulate this data.
 A cursor can hold more than one row, but can process only
one row at a time. The set of rows the cursor holds is called
the active set.
Types of cursors in PL/SQL:

 There are two types of cursors in PL/SQL:


 Implicit cursors
These are created by default when DML statements like, INSERT, UPDATE,
and DELETE statements are executed. They are also created when a
SELECT statement that returns just one row is executed.
 Explicit cursors
They must be created when you are executing a SELECT statement that
returns more than one row. Even though the cursor stores multiple records,
only one record can be processed at a time, which is called as current row.
When you fetch a row the current row position moves to next row.
Implicit cursor attributes

 Oracle provides few attributes called as implicit cursor attributes to


check the status of DML operations. The cursor attributes available
are %FOUND, %NOTFOUND, %ROWCOUNT, and %ISOPEN.
 For example, When you execute INSERT, UPDATE, or DELETE
statements the cursor attributes tell us whether any rows are
affected and how many have been affected.
When a SELECT... INTO statement is executed in a PL/SQL Block,
implicit cursor attributes can be used to find out whether any row
has been returned by the SELECT statement. PL/SQL returns an
error when no data is selected.
Consider the PL/SQL Block that uses implicit
cursor attributes as shown below:
DECLARE var_rows number(5);
BEGIN
UPDATE employee
SET salary = salary + 1000;
IF SQL%NOTFOUND THEN
dbms_output.put_line('None of the salaries where updated');
ELSIF SQL%FOUND THEN
var_rows := SQL%ROWCOUNT;
dbms_output.put_line('Salaries for ' || var_rows || 'employees are updated');
END IF;
END;
Explicit Cursors

 An explicit cursor is defined in the declaration section of the PL/SQL


Block.
 It is created on a SELECT Statement which returns more than one row.
We can provide a suitable name for the cursor.
 General Syntax for creating a cursor is as given below:
CURSOR cursor_name IS select_statement;  

cursor_name – A suitable name for the cursor.


select_statement – A select query which returns multiple rows.
 
How to use Explicit Cursor

There are four steps in using an Explicit Cursor.


 DECLARE the cursor in the declaration section.
 OPEN the cursor in the Execution Section.
 FETCH the data from cursor into PL/SQL variables or records
in the Execution Section.
 CLOSE the cursor in the Execution Section before you end the
PL/SQL Block.
Cursor syntax

General Syntax to open a cursor is:


 OPEN cursor_name;
 FETCH cursor_name INTO record_name; OR

 FETCH cursor_name INTO variable_list; General Syntax to close


a cursor is:
 CLOSE cursor_name;
General Form of using an explicit cursor

DECLARE
variables;
records;
create a cursor;
BEGIN
OPEN cursor;
FETCH cursor;
process the records;
CLOSE cursor;
END;
Explicit cursor

 DECLARE
 emp_rec emp_tbl%rowtype;
 CURSOR emp_cur IS
 SELECT *
 FROM
 WHERE salary > 10;
BEGIN
OPEN emp_cur;
 FETCH emp_cur INTO emp_rec;
dbms_output.put_line (emp_rec.first_name || ' ' || emp_rec.last_name);
 CLOSE emp_cur;
 END;
Explicit Cursor Attributes

 Oracle provides some attributes known as Explicit Cursor


Attributes to control the data processing while using
cursors. We use these attributes to avoid errors while
accessing cursors through OPEN, FETCH and CLOSE
Statements.
When does an error occur while accessing
an explicit cursor?
 a) When we try to open a cursor which is not closed in the
previous operation.
b) When we try to fetch a cursor after the last operation.
Explicit cursor attribute
Using Loops with Explicit Cursors:
 DECLARE
 CURSOR emp_cur IS
 SELECT first_name, last_name, salary FROM emp_tbl;
 emp_rec emp_cur%rowtype;
 BEGIN
 IF NOT sales_cur%ISOPEN THEN
 OPEN sales_cur;
 END IF;
 LOOP
 FETCH emp_cur INTO emp_rec;
 EXIT WHEN emp_cur%NOTFOUND;
 dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
 || ' ' ||emp_cur.salary);
 END LOOP;
 END;
 /
Cursor with a While Loop
 DECLARE
 CURSOR emp_cur IS
 SELECT first_name, last_name, salary FROM emp_tbl;
 emp_rec emp_cur%rowtype;
 BEGIN
 IF NOT sales_cur%ISOPEN THEN
 OPEN sales_cur;
 END IF;
 FETCH sales_cur INTO sales_rec;
 WHILE sales_cur%FOUND THEN
 LOOP
 dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
 || ' ' ||emp_cur.salary);
 FETCH sales_cur INTO sales_rec;
 END LOOP;
 END;
 /
Cursor with a FOR Loop:

General Syntax for using FOR LOOP:


 FOR record_name IN cusror_name
 LOOP process the row...
 END LOOP;
Cursor with a FOR Loop:
 DECLARE
 CURSOR emp_cur IS
 SELECT first_name, last_name, salary FROM emp_tbl;
 emp_rec emp_cur%rowtype;
 BEGIN
 IF NOT sales_cur%ISOPEN THEN
 OPEN sales_cur;
 END IF;
 DECLARE
 CURSOR emp_cur IS
 SELECT first_name, last_name, salary FROM emp_tbl;
 emp_rec emp_cur%rowtype;
 BEGIN
 FOR emp_rec in sales_cur
 LOOP
 dbms_output.put_line(emp_cur.first_name || ' ' ||emp_cur.last_name
 || ' ' ||emp_cur.salary);
 END LOOP;
 END;
 /
Trigger

 Triggers are stored program which are invoked by Oracle engine


automatically whenever a specified event occurs
 Triggers are written to be executed in response to any of the
following events
 A database manipulation (DML) statement (Delete,Insert,or
Update).
 A database definition (DDL) statement(Create ,ALTER, or Drop).
 Triggers could be defined on the table,view,schema or
database with which the event is associated.
Syntax of Trigger

 CREATE [OR REPLACE ] TRIGGER trigger_name


 {BEFORE | AFTER | INSTEAD OF }
 {INSERT [OR] | UPDATE [OR] | DELETE}
 [OF col_name]
 ON table_name
 [REFERENCING OLD AS o NEW AS n]
 [FOR EACH ROW]
 WHEN (condition)
 BEGIN
 --- sql statements
 END;
Explanation of syntax

 CREATE [OR REPLACE ] TRIGGER trigger_ name - This clause creates a


trigger with the given name or overwrites an existing trigger with the
same name.
 {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time
should the trigger get fired. i.e. for example: before or after updating a
table. INSTEAD OF is used to create a trigger on a view. before and after
cannot be used to create a trigger on a view.
 {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the
triggering event. More than one triggering events can be used together
separated by OR keyword. The trigger gets fired at all the specified
triggering event.
 [OF col_name] - This clause is used with update triggers. This clause is used
when you want to trigger an event only when a specific column is updated.
 [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old
and new values of the data being changed. By default, you reference the
values as :old.column_name or :new.column_name.
 [FOR EACH ROW] - This clause is used to determine whether a trigger must
fire when each row gets affected ( i.e. a Row Level Trigger) or just once when
the entire sql statement is executed(i.e.statement level Trigger).
 WHEN (condition) - This clause is valid only for row level triggers. The trigger
is fired only for rows that satisfy the condition specified.
 For Example: The price of a product changes constantly. It is
important to maintain the history of the prices of the
products.
 We can create a trigger to update the 'product_price_history'
table when the price of the product is updated in the 'product'
table.
Create the 'product' table and
'product_price_history' table
 CREATE TABLE product_price_history
 (product_id number(5),
 product_name varchar2(32),
 supplier_name varchar2(32),
 unit_price number(7,2) );
  
 CREATE TABLE product
 (product_id number(5),
 product_name varchar2(32),
 supplier_name varchar2(32),
 unit_price number(7,2) );
Create the price_history_trigger and
execute it.
CREATE or REPLACE TRIGGER price_history_trigger
BEFORE UPDATE OF unit_price
ON product
FOR EACH ROW
BEGIN
INSERT INTO product_price_history
VALUES
(:old.product_id,
:old.product_name,
:old.supplier_name,
:old.unit_price);
END;
/
Lets update the price of a product.

 UPDATE PRODUCT SET unit_price = 800 WHERE product_id =


100

 Once the above update query is executed, the trigger fires and
updates the 'product_price_history' table.
 If you ROLLBACK the transaction before committing to the
database, the data inserted to the table is also rolled back
Types of PL/SQL Triggers

 There are two types of triggers based on the which level it is


triggered.
1) Row level trigger - An event is triggered for each row
upated, inserted or deleted.
2) Statement level trigger - An event is triggered for each sql
statement executed.

 Note: if FOR EACH ROW clause is written that means trigger


is row level else if not written then it is statement level trigger
 Instead of trigger in Oracle

 An INSTEAD OF trigger is a trigger that allows you to update


data in tables via their view which cannot be modified directly
through DML statements.
 In Oracle, you can create an INSTEAD OF trigger for a view
only. You cannot create an INSTEAD OF trigger for a table.
Dropping Tigger

 Drop Trigger new_customer_trg;

 Alter Trigger new_customer_trg;


{disable|enable};
 https://way2tutorial.com/plsql/plsql-user-defined-exception.p
hp

You might also like