PL-SQL - Part2: Exception Handling Procedure Function Cursors Trigger
PL-SQL - Part2: Exception Handling Procedure Function Cursors Trigger
• Exception Handling
• Procedure
• Function
• Cursors
• Trigger
Exception handling
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
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
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