0% found this document useful (0 votes)
2 views

SQL Unit3 Notes

The document discusses exception handling in PL/SQL, detailing the types of exceptions, syntax for handling them, and examples of both system-defined and user-defined exceptions. It explains how to raise exceptions, use predefined exceptions, and manage cursors in PL/SQL. Additionally, it covers the creation of procedures and the use of parameters in those procedures.

Uploaded by

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

SQL Unit3 Notes

The document discusses exception handling in PL/SQL, detailing the types of exceptions, syntax for handling them, and examples of both system-defined and user-defined exceptions. It explains how to raise exceptions, use predefined exceptions, and manage cursors in PL/SQL. Additionally, it covers the creation of procedures and the use of parameters in those procedures.

Uploaded by

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

Exception Handling:

Error: condn which terminate program execution

1. Compile time
2. Run time

Exception defines error condition

Error code and name associated to it.

Exception -- An error occurs during the program execution is called Exception.

PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.

There are two type of exceptions:

o System-defined Exceptions
o User-defined Exceptions

Exception Handling

Syntax for exception handling:

Following is a general syntax for exception handling:

1. DECLARE
2. <declarations section>
3. BEGIN
4. <executable command(s)>
5. EXCEPTION
6. <exception handling goes here >
7. WHEN exception1 THEN
8. exception1-handling-statements
9. WHEN exception2 THEN
10. exception2-handling-statements
11. WHEN exception3 THEN
12. exception3-handling-statements
13. ........
14. WHEN others THEN
15. exception3-handling-statements
16. END;

Example of exception handling

Let's take a simple example to demonstrate the concept of exception handling using the
already created CUSTOMERS table.
SELECT* FROM CUSTOMERS;

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

4 Chandan 25 Noida 26000

5 Alex 21 Paris 28000

6 Sunita 20 Delhi 30000

1. DECLARE
2. c_id customers.id%type := 8;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /

After the execution of above code at SQL Prompt, it produces the following result:

No such customer!
PL/SQL procedure successfully completed.

The above program should show the name and address of a customer as result whose ID is
given. But there is no customer with ID value 8 in our database, so the program raises the
run-time exception NO_DATA_FOUND, which is captured in EXCEPTION block.
Note: You get the result "No such customer" because the customer_id used in the above
example is 8 and there is no cutomer having id value 8 in that table.

If you use the id defined in the above table (i.e. 1 to 6), you will get a certain result. For a
demo example: here, we are using the id 5.

1. DECLARE
2. c_id customers.id%type := 5;
3. c_name customers.name%type;
4. c_addr customers.address%type;
5. BEGIN
6. SELECT name, address INTO c_name, c_addr
7. FROM customers
8. WHERE id = c_id;
9. DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
10. DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
11. EXCEPTION
12. WHEN no_data_found THEN
13. dbms_output.put_line('No such customer!');
14. WHEN others THEN
15. dbms_output.put_line('Error!');
16. END;
17. /

After the execution of above code at SQL prompt, you will get the following result:

Name: alex
Address: paris
PL/SQL procedure successfully completed.

Raising Exceptions

In the case of any internal database error, exceptions are raised by the database server
automatically. But it can also be raised explicitly by programmer by using command RAISE.

Syntax for raising an exception:

1. DECLARE
2. exception_name EXCEPTION;
3. BEGIN
4. IF condition THEN
5. RAISE exception_name;
6. END IF;
7. EXCEPTION
8. WHEN exception_name THEN
9. statement;
10. END;

User-defined Exceptions

PL/SQL facilitates their users to define their own exceptions according to the need of the
program. A user-defined exception can be raised explicitly, using either a RAISE statement
or the procedure DBMS_STANDARD.RAISE_APPLICATION_ERROR.

Syntax for user define exceptions

1. DECLARE
2. my-exception EXCEPTION;

Pre-defined Exceptions

There are many pre-defined exception in PL/SQL which are executed when any database rule
is violated by the programs.

For example: NO_DATA_FOUND is a pre-defined exception which is raised when a


SELECT INTO statement returns no rows.

Following is a list of some important pre-defined exceptions:

Exception Oracle SQL Description


Error Code

ACCESS_INTO_NULL 06530 -6530 It is raised when a NULL object is


automatically assigned a value.

CASE_NOT_FOUND 06592 -6592 It is raised when none of the choices in


the "WHEN" clauses of a CASE
statement is selected, and there is no
else clause.

COLLECTION_IS_NULL 06531 -6531 It is raised when a program attempts to


apply collection methods other than
exists to an uninitialized nested table or
varray, or the program attempts to
assign values to the elements of an
uninitialized nested table or varray.

DUP_VAL_ON_INDEX 00001 -1 It is raised when duplicate values are


attempted to be stored in a column with
unique index.
INVALID_CURSOR 01001 -1001 It is raised when attempts are made to
make a cursor operation that is not
allowed, such as closing an unopened
cursor.

INVALID_NUMBER 01722 -1722 It is raised when the conversion of a


character string into a number fails
because the string does not represent a
valid number.

LOGIN_DENIED 01017 -1017 It is raised when s program attempts to


log on to the database with an invalid
username or password.

NO_DATA_FOUND 01403 +100 It is raised when a select into statement


returns no rows.

NOT_LOGGED_ON 01012 -1012 It is raised when a database call is


issued without being connected to the
database.

PROGRAM_ERROR 06501 -6501 It is raised when PL/SQL has an


internal problem.

ROWTYPE_MISMATCH 06504 -6504 It is raised when a cursor fetches value


in a variable having incompatible data
type.

SELF_IS_NULL 30625 -30625 It is raised when a member method is


invoked, but the instance of the object
type was not initialized.

STORAGE_ERROR 06500 -6500 It is raised when PL/SQL ran out of


memory or memory was corrupted.

TOO_MANY_ROWS 01422 -1422 It is raised when a SELECT INTO


statement returns more than one row.

VALUE_ERROR 06502 -6502 It is raised when an arithmetic,


conversion, truncation, or size-
constraint error occurs.
ZERO_DIVIDE 01476 1476 It is raised when an attempt is made to
divide a number by zero.

User- defined exceptions:

----exceptions are raised explicitly using Raise statement.

----also we have to declare these exceptions in declaration section

----write a exception handler for the exception

Declare
Exception_name exception;
Begin
Raise exception_name;
Exception
When exception_name then
Sql n pl/sql statements;
End;

Ex:

Declare
ABC exception;
Begin
Raise ABC;
Exception
When ABC then
Dbms_output.put_line(„Error occurred…..‟);
End;

Declare
Vsal number(5):=1000;
Vcomm number(5):=3000;
INVALID_COMMISSION exception;
Begin
If vcomm < vsal then
Insert into emp values(7600,‟Manish‟,‟Analyst‟,7689,vsal,vcomm,20);
Commit;
Else
Raise INVALID_COMMISSION;
End if;
Exception
When INVALID_COMMISSION then
Dbms_output.put_line(„Error….Commission cannot be greater than
salary…‟);
End;
RAISE_APPLICATION_ERROR function ---enable us to specify user-defined error
messages.

Syntax:

RAISE_APPLICATION_ERROR(<err_no>, <err_msg>,[keep errors])

Err_no ranges from 20,000 to -20,999

511 characters

Ex: RAISE_APPLICATION_ERROR(-20999,‟Contact administrator…‟)

Declare
Dup_deptno exception;
Ctr number;
Vdno number(5):=50;
Begin
Select count(*) into ctr from dept where deptno=50;
If ctr > 1 then
Raise dup_deptno;
Else
Insert into dept values(vdno,‟new name‟,‟new loc‟);
End if;
Exception
When dup_deptno then
Insert into error_log values(„Department already exists..‟);
When others then
RAISE_APPLICATION_ERROR(-20999,‟Contact administrator…‟);
End;

SQLCODE and SQLERRM fuctions:

To retrieve information about error

SQLCODE----returns code of the error.

-ve value

+ve value is returned in case of ORA-1403 NO_DATA_FOUND (100)

SQLERRM()----returns error msg

We can pass error no. as a argument to this func.

Ex: SQLERRM(100) ---NO_DATA_FOUND

SQLERRM(-50)---ORA-00050—Operating system error

SQLERRM(0)---Successful completion
SQLERRM(50)---non-Oracle exception

Exception Propogation:

Ex:

Declare
/*outer block*/
<declaration statements>
Begin
<statements>
Declare
/*Middle block*/
<declaration statements>
Begin
<statements>
End;
Begin
<statements>
Exception_outer
------
End;
End;

It is a process which determines the sections where the exceptions raised in various sections
should be handled.

If an exception is raised in inner block then exception handler is executed defined in inner
block.

Cursors:

Cursors are used to manage private work areas in the memory to store currently executing
SQL statements.

Types of cursors:

Implicit cursor----

Explicit cursor---

Program to implement Cursor:

Declare
C_eno emp.empno%type;
C_name emp.ename%type;
C_sal emp.sal%type;
Cursor emp_cur is select empno,ename,sal from emp;
Begin
Open emp_cur;
Dbms_output.put_line(„Employee no.‟,‟Employee Name‟,‟Emp_Salary‟);
loop
fetch emp_cur into c_eno,c_ename,c_sal;
dbms_output.put_line(c_eno||” “||c_ename||” “||c_sal);
end loop;
close emp_cur;
end;

emp table:

emp_cur

c_eno/empno c_ename/ename c_sal/sal

101 XXX 3000

102 YYY 4000

103 ZZZ 5000

Employee no. Employee name Emp_Salary

101 XXX 3000---rec_cur

102 YYY 4000

103 ZZZ 5000

Using %rowtype:

Program to implement Cursor:

Declare

Cursor emp_cur is select empno,ename,sal from emp;

Rec_cur emp_cur%rowtype;

Begin

Open emp_cur;

Dbms_output.put_line(„Employee no.‟,‟Employee Name‟,‟Emp_Salary‟);

loop

fetch emp_cur into rec_cur;

dbms_output.put_line(rec_cur.empno||” “||rec_cur.ename||” “||rec_cur.sal);

end loop;

close emp_cur;
end;

Attributes of explicit cursor:

%FOUND=TRUE when last fetch statement successfully retrieve the data.

%NOTFOUND=TRUE when last fetch statement executed failed to retrieve the data.

%ROWCOUNT=specifies no. of rows fetched from the cursor.

%ISOPEN=determine whether the cursor is open or not. It returns TRUE when cursor is
currently open.

Declare
Cursor emp_cur is select empno,ename,sal from emp;
Rec_cur emp_cur%rowtype;
Begin
Open emp_cur;
If emp_cur%isopen then
Dbms_output.put_line(„Employee no.‟,‟Employee Name‟,‟Emp_Salary‟);
loop
fetch emp_cur into rec_cur;
if emp_cur%found then
dbms_output.put_line(rec_cur.empno||” “||rec_cur.ename||” “||rec_cur.sal);
else
dbms_output.put_line(„Record not found…‟);
end if;

end loop;
close emp_cur;
else
dbms_output.put_line(„Cursor not opened…‟);
end if;
end;

Attributes of Implicit cursor:

Whenever we are executing DML statement inside PL/SQL block, Oracle automatically
opens an implicit cursor for that DML statement.

%FOUND==evaluates true. When previous DML statement is executed successfully.

%NOTFOUND== evaluates true. When previous DML statement is not executed


successfully.

%ISOPEN==false

%ROWCOUNT===no. of rows
Are used to get the info. Abt most recently executed DML statement.

SQL with attribute is used to get the info. Abt the implicit cursor.

Ex:

Declare

Eno emp.emp_no%type;

Begin

Eno:=&emp_no;

If SQL%isopen then

Dbms_output.put_line(„Not true….‟);

End if;

Update emp set sal=sal+500 where emp_no=eno;

If SQL%found then

Dbms_output.put_line(„record found...‟);

Else

Dbms_output.put_line(„Record not found…‟);

Clauses for explicit cursor:

For update clause: to apply row level locks on records fetched from the database tables

Explicitly locks the records stored in a privatework area,pointed by cursor

Apply exclusive lock

When open statement is used then lock is applied.

Ex:

Declare
Cursor emp_cur is select empno,ename,sal from emp for update of sal;
Rec_cur emp_cur%rowtype;
Begin
Open emp_cur;
If emp_cur%isopen then
Dbms_output.put_line(„Employee no.‟,‟Employee Name‟,‟Emp_Salary‟);
loop
fetch emp_cur into rec_cur;
if rec_cur.sal is NULL then
update emp set sal=0;
end if;
close emp_cur;
open emp_cur
loop
fetch emp_cur into rec_cur;
dbms_output.put_line(rec_cur.empno||” “||rec_cur.ename||” “||rec_cur.sal);
end if;
end loop;
close emp_cur;
else
dbms_output.put_line(„Cursor not opened…‟);
end if;
end;

Oracle Procedures

A procedure is a group of PL/SQL statements that can be called by name. The call
specification (sometimes called call spec) specifies a java method or a third-generation
language routine so that it can be called from SQL and PL/SQL.

Create Procedure

Syntax

1. CREATE [OR REPLACE] PROCEDURE procedure_name


2. [ (parameter [,parameter]) ]
3. IS
4. [declaration_section]
5. BEGIN
6. executable_section
7. [EXCEPTION
8. exception_section]
9. END [procedure_name];

Following are the three types of procedures that must be defined to create a procedure.

o IN: It is a default parameter. It passes the value to the subprogram.


o OUT: It must be specified. It returns a value to the caller.
o IN OUT: It must be specified. It passes an initial value to the subprogram and returns
an updated value to the caller.

Oracle Create procedure example

In this example, we are going to insert record in the "user" table. So you need to create user
table first.

Table creation:
1. create table user(id number(10) primary key,name varchar2(100));

Now write the procedure code to insert record in user table.

Procedure Code:

1. create or replace procedure "INSERTUSER"


2. (id IN NUMBER,
3. name IN VARCHAR2)
4. is
5. begin
6. insert into user values(id,name);
7. end;
8. /

Output:

Procedure created.

Oracle program to call procedure

Let's see the code to call above created procedure.

1. BEGIN
2. insertuser(101,'Rahul');
3. dbms_output.put_line('record inserted successfully');
4. END;
5. /

Now, see the "USER" table, you will see one record is inserted.

ID Name

101 Rahul

Oracle Drop Procedure

Syntax

1. DROP PROCEDURE procedure_name;

Example to drop procedure

1. DROP PROCEDURE pro1;


Oracle Function

A function is a subprogram that is used to return a single value. You must declare and define
a function before invoking it. It can be declared and defined at a same time or can be declared
first and defined later in the same block.

CREATE function in Oracle

Syntax

1. CREATE [OR REPLACE] FUNCTION function_name


2. [ (parameter [,parameter]) ]
3. RETURN return_datatype
4. IS | AS
5. [declaration_section]
6. BEGIN
7. executable_section
8. [EXCEPTION
9. exception_section]
10. END [function_name];

You must have define some parametrs before creating a procedure or a function. These
parameters are

o IN: It is a default parameter. It passes the value to the subprogram.


o OUT: It must be specified. It returns a value to the caller.
o IN OUT: It must be specified. It passes an initial value to the subprogram and returns
an updated value to the caller.

Oracle Function Example

Let's see a simple example to create a function.

1. create or replace function adder(n1 in number, n2 in number)


2. return number
3. is
4. n3 number(8);
5. begin
6. n3 :=n1+n2;
7. return n3;
8. end;
9. /

Now write another program to call the function.


1. DECLARE
2. n3 number(2);
3. BEGIN
4. n3 := adder(11,22);
5. dbms_output.put_line('Addition is: ' || n3);
6. END;
7. /

Output:

Addition is: 33
Statement processed.
0.05 seconds

Another Oracle Function Example

Let's take an example to demonstrate Declaring, Defining and Invoking a simple PL/SQL
function which will compute and return the maximum of two values.

1. DECLARE
2. a number;
3. b number;
4. c number;
5. FUNCTION findMax(x IN number, y IN number)
6. RETURN number
7. IS
8. z number;
9. BEGIN
10. IF x > y THEN
11. z:= x;
12. ELSE
13. Z:= y;
14. END IF;
15.
16. RETURN z;
17. END;
18. BEGIN
19. a:= 23;
20. b:= 45;
21.
22. c := findMax(a, b);
23. dbms_output.put_line(' Maximum of (23,45): ' || c);
24. END;
25. /
Output:

Maximum of (23,45): 45
Statement processed.
0.02 seconds

Oracle function example using table

Let's take a customer table. This example illustrates creating and calling a standalone
function. This function will return the total number of CUSTOMERS in the customers table.

Create customers table and have records in it.

Customers

Id Name Department Salary

1 alex web developer 35000

2 ricky program developer 45000

3 mohan web designer 35000

4 dilshad database manager 44000

Create Function:

1. CREATE OR REPLACE FUNCTION totalCustomers


2. RETURN number IS
3. total number(2) := 0;
4. BEGIN
5. SELECT count(*) into total
6. FROM customers;
7. RETURN total;
8. END;
9. /

After the execution of above code, you will get the following result.

Function created.

Calling Oracle Function:

1. DECLARE
2. c number(2);
3. BEGIN
4. c := totalCustomers();
5. dbms_output.put_line('Total no. of Customers: ' || c);
6. END;
7. /

After the execution of above code in SQL prompt, you will get the following result.

Total no. of Customers: 4


PL/SQL procedure successfully completed.

Oracle Recursive Function

You already know that a program or a subprogram can call another subprogram. When a
subprogram calls itself, it is called recursive call and the process is known as recursion.

Example to calculate the factorial of a number

Let's take an example to calculate the factorial of a number. This example calculates the
factorial of a given number by calling itself recursively.

1. DECLARE
2. num number;
3. factorial number;
4.
5. FUNCTION fact(x number)
6. RETURN number
7. IS
8. f number;
9. BEGIN
10. IF x=0 THEN
11. f := 1;
12. ELSE
13. f := x * fact(x-1);
14. END IF;
15. RETURN f;
16. END;
17.
18. BEGIN
19. num:= 6;
20. factorial := fact(num);
21. dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
22. END;
23. /
After the execution of above code at SQL prompt, it produces the following result.

Factorial 6 is 720
PL/SQL procedure successfully completed.

Oracle Drop Function

If you want to remove your created function from the database, you should use the following
syntax.

Syntax:

1. DROP FUNCTION function_name;

Cursor

A cursor is a pointer to a private SQL area that stores information about the processing of a
SELECT or DML statements like INSERT, UPDATE, DELETE or MERGE.

Cursor is a mechanism which facilitates you to assign a name to a SELECT statement and
manipulate the information within that SQL statement.

How to declare cursor

Syntax

1. CURSOR cursor_name
2. IS
3. SELECT_statement;

Let's see how to define a cursor called c1. We are using a table name "course" having
columns "course_id" and "course_name".

Example

1. CURSOR c1
2. IS
3. SELECT course_id
4. FROM courses
5. WHERE course_name = name_in;

In the above example, the result set of this cursor is all course_id whose course_name
matches the variable called name_in.

How to use cursor in a function

Example
1. CREATE OR REPLACE Function FindCourse
2. ( name_in IN varchar2 )
3. RETURN number
4. IS
5. cnumber number;
6. CURSOR c1
7. IS
8. SELECT course_id
9. FROM courses
10. WHERE course_name = name_in;
11. BEGIN
12. OPEN c1;
13. FETCH c1 INTO cnumber;
14. if c1%notfound then
15. cnumber := 9999;
16. end if;
17. CLOSE c1;
18. RETURN cnumber;
19. END;

Output

Function created.
0.09 seconds

Opening a cursor

After the declaration of the cursor, you have to use the open statement to open the cursor.

Syntax

1. OPEN cursor_name;

Example

1. OPEN c1;

How to use open cursor in a function

This function specifies how to use the open statement.

Example

1. CREATE OR REPLACE Function FindCourse


2. ( name_in IN varchar2 )
3. RETURN number
4. IS
5. cnumber number;
6. CURSOR c1
7. IS
8. SELECT course_id
9. FROM courses
10. WHERE course_name = name_in;
11. BEGIN
12. OPEN c1;
13. FETCH c1 INTO cnumber;
14. if c1%notfound then
15. cnumber := 9999;
16. end if;
17. CLOSE c1;
18. RETURN cnumber;
19. END;

Output

Function created.
0.09 seconds

How to fetch rows from cursor

This statement is used after declaring and opening your cursor. It is used to fetch rows from
cursor.

Syntax

1. FETCH cursor_name INTO variable_list;

Parameters

1) cursor_name:It specifies the name of the cursor that you wish to fetch rows.

2) variable_list: It specifies the list of variables that you wish to store the cursor result set in.

Example:

Consider a cursor defined as

1. CURSOR c1
2. IS
3. SELECT course_id
4. FROM courses
5. WHERE course_name = name_in;
Statement used for fetching data

1. FETCH c1 into cnumber;

Let's take an example to fetch course_id into the variable called cnumber.

1. CREATE OR REPLACE Function FindCourse


2. ( name_in IN varchar2 )
3. RETURN number
4. IS
5. cnumber number;
6. CURSOR c1
7. IS
8. SELECT course_id
9. FROM courses
10. WHERE course_name = name_in;
11. BEGIN
12. OPEN c1;
13. FETCH c1 INTO cnumber;
14. if c1%notfound then
15. cnumber := 9999;
16. end if;
17. CLOSE c1;
18. RETURN cnumber;
19. END;

Closing a cursor

CLOSE statement is a final step and it is used to close the cursor once you have finished
using it.

Syntax

1. CLOSE cursor_name;

Statement for closing cursor

1. CLOSE c1;

Example

The following example specifies how to close the cursor.

1. CREATE OR REPLACE Function FindCourse


2. ( name_in IN varchar2 )
3. RETURN number
4. IS
5. cnumber number;
6. CURSOR c1
7. IS
8. SELECT course_id
9. FROM courses
10. WHERE course_name = name_in;
11. BEGIN
12. OPEN c1;
13. FETCH c1 INTO cnumber;
14. if c1%notfound then
15. cnumber := 9999;
16. end if;
17. CLOSE c1;
18. RETURN cnumber;
19. END;

Cursor within cursor

It is also possible to declare a cursor within a cursor. the following example specifies how to
declare a cursor within a cursor.

In this example, there is a cursor named get_tables that retrieves the owner and table_name
values. These values are then used in a second cursor called get_columns.

Example

1. CREATE OR REPLACE PROCEDURE MULTIPLE_CURSORS_PROC is


2. v_owner varchar2(40);
3. v_table_name varchar2(40);
4. v_column_name varchar2(100);
5.
6. /* First cursor */
7. CURSOR get_tables IS
8. SELECT DISTINCT tbl.owner, tbl.table_name
9. FROM all_tables tbl
10. WHERE tbl.owner = 'SYSTEM';
11.
12. /* Second cursor */
13. CURSOR get_columns IS
14. SELECT DISTINCT col.column_name
15. FROM all_tab_columns col
16. WHERE col.owner = v_owner
17. AND col.table_name = v_table_name;
18.
19. BEGIN
20.
21. -- Open first cursor
22. OPEN get_tables;
23. LOOP
24. FETCH get_tables INTO v_owner, v_table_name;
25.
26. -- Open second cursor
27. OPEN get_columns;
28. LOOP
29. FETCH get_columns INTO v_column_name;
30. END LOOP;
31. CLOSE get_columns;
32. END LOOP;
33. CLOSE get_tables;
34. EXCEPTION
35. WHEN OTHERS THEN
36. raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
37. end MULTIPLE_CURSORS_PROC;

Output

Procedure created.
0.16 seconds
Note: You have to continuously open and close the second cursor each time a new record is
retrieved from the first cursor. That way, the second cursor will use the new variable values
from the first cursor.

Trigger

Trigger is invoked by Oracle engine automatically whenever a specified event occurs.Trigger


is stored into database and invoked repeatedly, when specific condition match.

Triggers are stored programs, which are automatically executed or fired when some event
occurs.

Triggers are written to be executed in response to any of the following events.

o A database manipulation (DML) statement (DELETE, INSERT, or UPDATE).


o A database definition (DDL) statement (CREATE, ALTER, or DROP).
o A database operation (SERVERERROR, LOGON, LOGOFF, STARTUP, or
SHUTDOWN).

Triggers could be defined on the table, view, schema, or database with which the event is
associated.

Advantages of Triggers

These are the following advantages of Triggers:

o Trigger generates some derived column values automatically


o Enforces referential integrity
o Event logging and storing information on table access
o Auditing
o Synchronous replication of tables
o Imposing security authorizations
o Preventing invalid transactions

Creating a trigger:

Syntax for creating trigger:

1. CREATE [OR REPLACE ] TRIGGER trigger_name


2. {BEFORE | AFTER | INSTEAD OF }
3. {INSERT [OR] | UPDATE [OR] | DELETE}
4. [OF col_name]
5. ON table_name
6. [REFERENCING OLD AS o NEW AS n]
7. [FOR EACH ROW]
8. WHEN (condition)
9. DECLARE
10. Declaration-statements
11. BEGIN
12. Executable-statements
13. EXCEPTION
14. Exception-handling-statements
15. END;

Here,

o CREATE [OR REPLACE] TRIGGER trigger_name: It creates or replaces an existing


trigger with the trigger_name.
o {BEFORE | AFTER | INSTEAD OF} : This specifies when the trigger would be
executed. The INSTEAD OF clause is used for creating trigger on a view.
o {INSERT [OR] | UPDATE [OR] | DELETE}: This specifies the DML operation.
o [OF col_name]: This specifies the column name that would be updated.
o [ON table_name]: This specifies the name of the table associated with the trigger.
o [REFERENCING OLD AS o NEW AS n]: This allows you to refer new and old
values for various DML statements, like INSERT, UPDATE, and DELETE.
o [FOR EACH ROW]: This specifies a row level trigger, i.e., the trigger would be
executed for each row being affected. Otherwise the trigger will execute just once
when the SQL statement is executed, which is called a table level trigger.
o WHEN (condition): This provides a condition for rows for which the trigger would
fire. This clause is valid only for row level triggers.

PL/SQL Trigger Example

Let's take a simple example to demonstrate the trigger. In this example, we are using the
following CUSTOMERS table:

Create table and have records:

ID NAME AGE ADDRESS SALARY

1 Ramesh 23 Allahabad 20000

2 Suresh 22 Kanpur 22000

3 Mahesh 24 Ghaziabad 24000

4 Chandan 25 Noida 26000

5 Alex 21 Paris 28000

6 Sunita 20 Delhi 30000

Create trigger:

Let's take a program to create 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:

1. CREATE OR REPLACE TRIGGER display_salary_changes


2. BEFORE DELETE OR INSERT OR UPDATE ON customers
3. FOR EACH ROW
4. WHEN (NEW.ID > 0)
5. DECLARE
6. sal_diff number;
7. BEGIN
8. sal_diff := :NEW.salary - :OLD.salary;
9. dbms_output.put_line('Old salary: ' || :OLD.salary);
10. dbms_output.put_line('New salary: ' || :NEW.salary);
11. dbms_output.put_line('Salary difference: ' || sal_diff);
12. END;
13. /

After the execution of the above code at SQL Prompt, it produces the following result.

Trigger created.

Check the salary difference by procedure:

Use the following code to get the old salary, new salary and salary difference after the trigger
created.

1. DECLARE
2. total_rows number(2);
3. BEGIN
4. UPDATE customers
5. SET salary = salary + 5000;
6. IF sql%notfound THEN
7. dbms_output.put_line('no customers updated');
8. ELSIF sql%found THEN
9. total_rows := sql%rowcount;
10. dbms_output.put_line( total_rows || ' customers updated ');
11. END IF;
12. END;
13. /

Output:

Old salary: 20000


New salary: 25000
Salary difference: 5000
Old salary: 22000
New salary: 27000
Salary difference: 5000
Old salary: 24000
New salary: 29000
Salary difference: 5000
Old salary: 26000
New salary: 31000
Salary difference: 5000
Old salary: 28000
New salary: 33000
Salary difference: 5000
Old salary: 30000
New salary: 35000
Salary difference: 5000
6 customers updated

Note: As many times you executed this code, the old and new both salary is incremented by
5000 and hence the salary difference is always 5000.

After the execution of above code again, you will get the following result.

Old salary: 25000


New salary: 30000
Salary difference: 5000
Old salary: 27000
New salary: 32000
Salary difference: 5000
Old salary: 29000
New salary: 34000
Salary difference: 5000
Old salary: 31000
New salary: 36000
Salary difference: 5000
Old salary: 33000
New salary: 38000
Salary difference: 5000
Old salary: 35000
New salary: 40000
Salary difference: 5000
6 customers updated

Important Points

Following are the two very important point and should be noted carefully.

o OLD and NEW references are used for record level triggers these are not avialable for
table level triggers.
o If you want 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.

In Oracle, you can define procedures that are implicitly executed when an INSERT,
UPDATE or DELETE statement is issued against the associated table. These procedures are
called database triggers.

Oracle Before INSERT/UPDATE/DELETE Trigger

This statement specifies that Oracle will fire this trigger BEFORE the INSERT/UPDATE or
DELETE operation is executed.

Syntax
1. CREATE [ OR REPLACE ] TRIGGER trigger_name
2. BEFORE INSERT or UPDATE or DELETE
3. ON table_name
4. [ FOR EACH ROW ]
5. DECLARE
6. -- variable declarations
7. BEGIN
8. -- trigger code
9. EXCEPTION
10. WHEN ...
11. -- exception handling
12. END;

Parameters

OR REPLACE: It is an optional parameter. It is used to re-create the trigger if it already


exists. It facilitates you to change the trigger definition without using a DROP TRIGGER
statement.

trigger_name: It specifies the name of the trigger that you want to create.

BEFORE INSERT or UPDATE or DELETE: It specifies that the trigger will be fired
before the INSERT or UPDATE or DELETE operation is executed.

table_name: It specifies the name of the table on which trigger operation is being performed.

Limitations

o BEFORE trigger cannot be created on a view.


o You cannot update the OLD values.
o You can only update the NEW values.

Oracle BEFORE Trigger Example

Consider, you have a "suppliers" table with the following parameters.

1. CREATE TABLE "SUPPLIERS"


2. ( "SUPPLIER_ID" NUMBER,
3. "SUPPLIER_NAME" VARCHAR2(4000),
4. "SUPPLIER_ADDRESS" VARCHAR2(4000)
5. )
6. /

You can use the following CREATE TRIGGER query to create a BEFORE INSERT or
UPDATE or DELETE Trigger:
1. CREATE OR REPLACE TRIGGER "SUPPLIERS_T1"
2. BEFORE
3. insert or update or delete on "SUPPLIERS"
4. for each row
5. begin
6. when the person performs insert/update/delete operations into the table.
7. end;
8. /
9. ALTER TRIGGER "SUPPLIERS_T1" ENABLE
10. /

Here the trigger name is "SUPPLIERS_T1" and it is fired BEFORE the insert or update or
delete operation is executed on the table "suppliers".

Oracle After INSERT/UPDATE/DELETE Trigger

This statement specifies that Oracle will fire this trigger AFTER the INSERT/UPDATE or
DELETE operation is executed.

Syntax

1. CREATE [ OR REPLACE ] TRIGGER trigger_name


2. AFTER INSERT or UPDATE or DELETE
3. ON table_name
4. [ FOR EACH ROW ]
5. DECLARE
6. -- variable declarations
7. BEGIN
8. -- trigger code
9. EXCEPTION
10. WHEN ...
11. -- exception handling
12. END;

Parameters

OR REPLACE: It is an optional parameter. It is used to re-create the trigger if it already


exists. It facilitates you to change the trigger definition without using a DROP TRIGGER
statement.
trigger_name: It specifies the name of the trigger that you want to create.

AFTER INSERT or UPDATE or DELETE: It specifies that the trigger will be fired after
the INSERT or UPDATE or DELETE operation is executed.

table_name: It specifies the name of the table on which trigger operation is being performed.

Limitations

o AFTER trigger cannot be created on a view.


o You cannot update the OLD values.
o You can only update the NEW values.

Oracle AFTER Trigger Example

Consider, you have a "suppliers" table with the following parameters.

1. CREATE TABLE "SUPPLIERS"


2. ( "SUPPLIER_ID" NUMBER,
3. "SUPPLIER_NAME" VARCHAR2(4000),
4. "SUPPLIER_ADDRESS" VARCHAR2(4000)
5. )
6. /

You can use the following CREATE TRIGGER query to create a AFTER INSERT or
UPDATE or DELETE Trigger:

1. CREATE OR REPLACE TRIGGER "SUPPLIERS_T2"


2. AFTER
3. insert or update or delete on "SUPPLIERS"
4. for each row
5. begin
6. when the person performs insert/update/delete operations into the table.
7. end;
8. /
9. ALTER TRIGGER "SUPPLIERS_T2" ENABLE
10. /

Here the trigger name is "SUPPLIERS_T2" and it is fired AFTER the insert or update or
delete operation is executed on the table "suppliers".
DROP Trigger

DROP TRIGGER statement is used to drop the trigger if you find that you need to remove it
from the database.

Syntax: DROP TRIGGER trigger_name;

Parameters

trigger_name: It specifies the name of the trigger that you want to drop.

Oracle DROP Trigger Example

1. DROP TRIGGER SUPPLIERS_T1;

It will drop the trigger name "SUPPLIERS_T1" from the table "SUPPLIERS".

ENABLE / DISABLE Trigger

The ALTER TRIGGER statement is used to disable a trigger.

Syntax

1. ALTER TRIGGER trigger_name DISABLE;

Parameters

trigger_name: It specifies the name of the trigger that you want to disable.

Oracle DISABLE Trigger Example

1. ALTER TRIGGER SUPPLIERS_T2 DISABLE;

This example will disable the trigger called "SUPPLIERS_T2" from the table "SUPPLIERS".

Oracle DISABLE ALL Triggers Example

If there is more than one trigger in a table and you want to disable all the triggers from the
database then you can do it by ALTER TABLE statement.

Syntax

1. ALTER TABLE table_name DISABLE ALL TRIGGERS;

Example

1. ALTER TABLE SUPPLIERS DISABLE ALL TRIGGERS;

This example will disable all triggers from the table "suppliers".
Oracle ENABLE Trigger

The ALTER TRIGGER statement is used to enable a trigger.

Syntax

1. ALTER TRIGGER trigger_name ENABLE;

Parameters

trigger_name: It specifies the name of the trigger that you want to enable.

Oracle ENABLE Trigger Example

1. ALTER TRIGGER SUPPLIERS_T1 ENABLE;

This example will enable the trigger named "SUPPLIERS_T1" in the "SUPPLIERS" table.

ADVERTISEMENT

Oracle ENABLE ALL Triggers Example

Syntax

1. ALTER TABLE table_name ENABLE ALL TRIGGERS;

Example

1. ALTER TABLE SUPPLIERS ENABLE ALL TRIGGERS;

This example will enable all the triggers on the table name "SUPPLIERS".

You might also like