Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

Experiment 7: Stored Procedures and Exception Handling.

Procedures: Procedures are named PL/SQL blocks that can take parameters, perform an
action and can be invoked. A procedure is generally used to perform an action and to pass
values. Procedures are made upof:
1. A declarative part
2. An executable part
3. An optional exception handlingpart
DeclarativePart: The declarative part may contain declaration ofcursors, constants, variables,
exceptions and subprograms. These objects are local to the procedure. The objects become
invalid once you exit fromit.
ExecutablePart: This part contains PL/SQL block consisting of statements that assign values,
control execution and manipulate ORACLEdata.
ExceptionHandlingPart: This part contains code that performs action to deal with exceptions
raised during the execution of theprogram.
Syntax
CREATE OR REPLACE
PROCEDURE [schema] procedure_name (argument{IN,OUT,INOUT}datatype){IS,AS}
Variabledeclarations;
Constant declarations; BEGIN
PL/SQL subprogram body; EXCEPTION
Exception PL/SQL block;
END;

Types of Procedures:
1. Local Procedure
2. Stored Procedure
Local Procedure: These procedures are declared within the PL/SQL block and called from
the begin section of the PL/SQL block.
The following is a simple example of a procedure:
Program:
declare
a number; b number; c number; d number; e number; f number;
procedureprocess(ainnumber,binnumber,coutnumber,doutnumber,eoutnumber,fout
number) is
begin c:=a+b; d:=a-b; e:=a*b; f:=a/b; end; begin a:=&firstnumber;
b:=&secondnumber;
process(a, b, c, d, e, f); DBMS_output.put_line(‘addition is’ || c);
DBMS_output.put_line(‘subtraction is’ || d);
DBMS_output.put_line(‘multiplicationis’||e); DBMS_output.put_line(‘divisionis’||f);

end;

OUTPUT

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 two types
of exceptions −System-defined exceptions, User-defined exceptions

Syntax:
WHEN exception THEN statement;
Program:
Experiment 8: Triggers and Cursor Management in PL/SQL
Triggers: A trigger is a special kind of stored procedure that is invoked whenever an attempt
is made tomodify the data in the table it protects. Triggers are automatically executed or fired
when some events occur. Modifications to the table are made using INSERT, UPDATE, OR
DELETE statements. Triggers are used to enforce data integrity and. business rules such
asautomatically updating summary data. It allows performing cascading delete or
updatingoperations. If constraints exist on the trigger table, they are checked prior to the
trigger execution. If constraints are violated statement will not be executed and trigger will
not run.Triggers are associated with tables and they are automatic. Triggers are automatically
invoked by SQL SERVER. Triggers prevent incorrect, unauthorized, or inconsistent
changestodata.
Uses of Triggers:
1. A trigger can permit DML statements against a table only if they are issued,
duringregular business hours or on predeterminedweekdays.
2. A trigger can also be used to keep an audit trail of a table.
3. It can be used to prevent invalid transactions.
4. Enforce complex security authorizations.
5. Exception handling.
6. Generation of primary key and foreignkey.
How to apply Triggers:
A trigger has three basic parts:
1. Triggering Event or Statement: It is a SQL statement that causes a trigger to be fired.
It can be an INSERT, UPDATE or DELETE statement for a specifictable.
2. Trigger Restriction: A trigger restriction specifies a Boolean expression that must be
TRUE for thetrigger to fire. It is an option available for triggers that are fired for each
row. Atrigger restriction is specified using a WHENclause.
3. Trigger Action: A trigger action is the PL/SQL code to be executed when a triggering
statement is encountered and any trigger restriction evaluates to TRUE.
Types of Triggers
• Row Triggers: A row trigger is fired each time the table is affected by the triggering
statement, for example, if an UPDATE statement update multiple rows of a table, a row
trigger is fired once for each row affected by the UPDATE statement.
• Statement Triggers: A row trigger is fired once on behalf of the triggering statement,
independent of the number of rows the triggering statement affects.
• Before Triggers: Before triggers execute the trigger action before the triggering statement.
These types of triggers are commonly used in the following situations:
1. BEFORE triggers are used when the trigger action should determine whether or not
the triggering statement should be allowed to complete. By using BEFORE trigger,
user can eliminate unnecessary processing of the triggering statement.
2. BEFORE triggers are used to derive specific column values before completing a
triggering INSERT or UPDATEstatement.
• After Triggers: After triggers execute the trigger after the triggering statement is
executed. These types of triggers are commonly used in the following situations:
1. AFTER triggers are used when the triggering statement should complete before
executing the triggeraction.
2. If a BEFORE trigger is already present, an AFTER trigger can perform different
actions on the same triggeringstatement.
CombinationsTriggers: Using the above triggers, four types of triggers could be created.
There are twelve combinations of triggers.
Before Statement Trigger: Before executing the triggering statement, the trigger action is
executed.
Before Row Trigger: Before modifying each row affected by the triggering statement and
BEFORE applying appropriate integrity constraints, the trigger is executed.
AfterStatementTrigger: After executing the triggering statement and applying and deferred
integrity constraints, the trigger action is executed.
After Row Trigger: After modifying each row affected by the triggering statement and
applying appropriate integrity constraints, the trigger action is executed for the current row.
Unlike BEFORE row triggers, AFTER row triggers have rowslocked.
Creation of Triggers: Triggers are created with the CREATE TRIGGER statement. This
statement specifies that on which table trigger is defined and on which events trigger will be
invoked.

Syntax:
DeletingaTrigger: To drop Trigger one can use DROP TRIGGER statement.
Syntax:
DROP TRIGGER < TriggerName>

Example
To start with, using the CUSTOMERS table Select * fromcustomers;

+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
|2|Khilan|25|Delhi|1500.00|
|3|kaushik|23|Kota|2000.00|
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+ + + + + +
The following program creates a row-level trigger for the customers table that would fire for

INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table.

This trigger will display the salary difference between the old values and new values−

CREATE OR REPLACE TRIGGER display_salary_changes

BEFORE DELETE OR INSERT OR UPDATE ON customers FOR EACHROW

WHEN (NEW.ID > 0) DECLARE


sal_diff number; BEGIN
sal_diff := :NEW.salary - :OLD.salary; dbms_output.put_line('Old salary: '

|| :OLD.salary); dbms_output.put_line('New salary: ' || :NEW.salary);

dbms_output.put_line('Salary difference: ' || sal_diff); END;

When the above code is executed at the SQL prompt, it produces the following result−Trigger

created.

The following points need to be considered here −

● OLD and NEW references are not available for table-level triggers, rather use them

for record-level triggers.

● To query the table in the same trigger, then you should use the AFTER keyword,

because, triggers can query the table or change it again only after the initial changes
are applied and the table is back in a consistent state.

● The above trigger has been written in such a way that it will fire before any DELETE

or INSERT or UPDATE operation on the table, but a trigger can be written on a


single or multiple operations, for example BEFORE DELETE, which will fire
whenever a record will be deleted using the DELETE operation on thetable.

Triggering a Trigger:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (7, ',Kriti', 22, 'HP', 7500.00 ); When a record is created in
the CUSTOMERS table, the above create trigger, display_salary_changes will be fired and it
will display the following result –Old salary:
New salary: 7500 Salary difference:
Because this is a new record, old salary is not available and the above result comes as null.
The UPDATE statement will update an existing record in the table–
UPDATEcustomers
SET salary = salary + 500

WHERE id = 2;
When a record is updated in the CUSTOMERS table, the above create trigger,

display_salary_changes will be fired and it will display the following result −

Old salary: 1500


New salary: 2000
Salary difference: 500

CURSORS:
Oracle DBA uses a work area for its internal processing. This work area is private to SQL’s
operations and is called Cursor.The data that is stored in the cursor is called the Active Data
Set. The size of the cursor in memory is the size required to hold the number of rows in the
active data set.
A PL/SQL block of code includes the Procedural code for looping and branching along with
the SQL statement. If records from a record set created using a select statement are to be
evaluated and processed one at a time, then the only method available is by using Explicit
Cursors.

TYPES OF CURSORS:

● Implicitcursors.

● Explicitcursors.

ATTRIBUTESOFCURSORS: Oracle provides certain attributes/ cursor variables to control


the exception of a cursor. Whenever any cursor is opened and used, Oracle creates a set of
four system variables via which Oracle keeps track of the ‘Current’ status of the cursor. We
can access these variables. The implicit and explicit cursors have four attributes as described
below:
1. %NOTFOUND: It evaluates to TRUE, if an insert, delete ,or update affected no rows or a
singlerow

select returns no rows. Otherwise, it evaluates to FALSE.


Syntax:
cursor_name%NOTFOUND;

2. %FOUND: It is the logical opposite of %notfound. It evaluates to TRUE, if an insert,


delete, or update affected one or more rows, or a single row select returns one or more
rows. Otherwise, it evaluates to FALSE.
Syntax:
cursor_name%FOUND;

3. %ISOPEN: Oracle automatically closes the SQL cursor after executing its associated
SQL statement. As a result, sql %isopen always evaluates to FALSE. If the explicit cursor
is open then it returns true otherwisefalse.

Syntax:
cursor_name%ISOPEN;

4. %ROWCOUNT: Returns the number of rows affected by an insert, delete ,or update or
select into statement.

Syntax:
cursor_name%ROWCOUNT;

IMPLICIT CURSORS:
Oracle implicitly opens a cursor to process each SQL statement not associated with an
explicitly declared cursor. PL/SQL lets us refer to the most recent implicit cursor as the SQL
cursor. So, although we cannot use the open, fetch, and close statements to control an implicit
cursor, we can still use cursor attributes to access information about the most recently
executed SQL statement.

Use cursor to select the five highest paid employees from the emp table showing tables also.
Input Table:

Declare

cursor c1 is selecte name, empno, sal from emp orderby sal desc; --start with highest paid
employee

my_ename varchar2(10);
my_empno number(4);
my_sal number(7,2);
Begin open c1;
for i in 1..5 loop
fetch c1intomy_ename, my_empno, my_sal;
exit whenc1%notfound;
insertintotempvalues(my_sal,my_empno,my_ename);
commit;
end loop;
close c1;
end;

Output Table:

You might also like