SQL Unit3 Notes
SQL Unit3 Notes
1. Compile time
2. Run time
PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.
o System-defined Exceptions
o User-defined Exceptions
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;
Let's take a simple example to demonstrate the concept of exception handling using the
already created CUSTOMERS table.
SELECT* FROM CUSTOMERS;
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.
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.
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.
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:
511 characters
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;
-ve value
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---
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
Using %rowtype:
Declare
Rec_cur emp_cur%rowtype;
Begin
Open emp_cur;
loop
end loop;
close emp_cur;
end;
%NOTFOUND=TRUE when last fetch statement executed failed to retrieve the data.
%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;
Whenever we are executing DML statement inside PL/SQL block, Oracle automatically
opens an implicit cursor for that DML statement.
%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;
If SQL%found then
Dbms_output.put_line(„record found...‟);
Else
For update clause: to apply row level locks on records fetched from the database tables
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
Following are the three types of procedures that must be defined to create a procedure.
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));
Procedure Code:
Output:
Procedure created.
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
Syntax
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.
Syntax
You must have define some parametrs before creating a procedure or a function. These
parameters are
Output:
Addition is: 33
Statement processed.
0.05 seconds
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
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.
Customers
Create Function:
After the execution of above code, you will get the following result.
Function created.
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.
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.
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.
If you want to remove your created function from the database, you should use the following
syntax.
Syntax:
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.
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.
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;
Example
Output
Function created.
0.09 seconds
This statement is used after declaring and opening your cursor. It is used to fetch rows from
cursor.
Syntax
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:
1. CURSOR c1
2. IS
3. SELECT course_id
4. FROM courses
5. WHERE course_name = name_in;
Statement used for fetching data
Let's take an example to fetch course_id into the variable called cnumber.
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;
1. CLOSE c1;
Example
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
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
Triggers are stored programs, which are automatically executed or fired when some event
occurs.
Triggers could be defined on the table, view, schema, or database with which the event is
associated.
Advantages of Triggers
Creating a trigger:
Here,
Let's take a simple example to demonstrate the trigger. In this example, we are using the
following CUSTOMERS table:
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:
After the execution of the above code at SQL Prompt, it produces the following result.
Trigger created.
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:
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.
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.
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
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
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".
This statement specifies that Oracle will fire this trigger AFTER the INSERT/UPDATE or
DELETE operation is executed.
Syntax
Parameters
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
You can use the following CREATE TRIGGER query to create a AFTER INSERT or
UPDATE or DELETE Trigger:
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.
Parameters
trigger_name: It specifies the name of the trigger that you want to drop.
It will drop the trigger name "SUPPLIERS_T1" from the table "SUPPLIERS".
Syntax
Parameters
trigger_name: It specifies the name of the trigger that you want to disable.
This example will disable the trigger called "SUPPLIERS_T2" from the table "SUPPLIERS".
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
Example
This example will disable all triggers from the table "suppliers".
Oracle ENABLE Trigger
Syntax
Parameters
trigger_name: It specifies the name of the trigger that you want to enable.
This example will enable the trigger named "SUPPLIERS_T1" in the "SUPPLIERS" table.
ADVERTISEMENT
Syntax
Example
This example will enable all the triggers on the table name "SUPPLIERS".