WEEK 4 - Chapter 4 Cursors and Exception Handling
WEEK 4 - Chapter 4 Cursors and Exception Handling
www.vut.ac.za
Vivian Mapande
1
www.vut.ac.za
CONTENTS
1. Manipulate data with cursors
• It manages the data specified by the SQL statement in the system global area
(SGA).
• The private work area contains information about the SQL statement and the set
of data returned or affected by that statement.
• PL/SQL provides a number of ways to name this work area and manipulate the
information within it, all of which involve defining and working with cursors.
3
Cursors and Exception Handling
4
Cursors and Exception Handling
1. Implicit cursors
• A simple and direct SELECT...INTO which retrieves a single row of data into local program
variables.
• Disadvantage
• It can often lead to coding the same or similar SELECTs in multiple places in your code.
• They are automatically created and managed by the database system when you execute a
SQL statement in PL/SQL.
• PL/SQL declares and manages an implicit cursor every time you execute a SQL DML
statement (INSERT, UPDATE, MERGE, or DELETE) or a SELECT INTO that returns a single
row from the database directly into a PL/SQL data structure.
5
Cursors and Exception Handling
FROM employees
6
Cursors and Exception Handling
• This is a SELECT statement that you declare as a cursor explicitly in your application code.
• You will generally use explicit cursors when you need to retrieve multiple rows from data
sources using static SQL.
• Declaration
• You declare an explicit cursor to define the SQL query that will be associated with the
cursor.
• The cursor declaration includes the SELECT statement and any parameters you want to
pass to the query.
7
• Opening
Cursors and Exception Handling
• Fetching
• Once the cursor is open, you can fetch rows from the result set one at a time or in a
loop. You can fetch data into variables and process it as needed.
• Closing
• After you've finished processing the result set, you should close the cursor to release
the associated resources and free up memory.
8
Cursors and Exception Handling
DECLARE
CURSOR cursor_name IS
SELECT column1, column2
FROM table_name
WHERE condition;
BEGIN
OPEN cursor_name;
FETCH cursor_name INTO variable1, variable2;
CLOSE cursor_name;
END;
9
Cursors and Exception Handling
1
0
Cursors and Exception Handling
1
1
Cursors and Exception Handling
return_type: Should be
the data type of the
TYPE cursor_variable_type IS REF CURSOR [RETURN return_type]; columns that will be
returned by the cursor
variable.
1
2
Cursors and Exception Handling
DECLARE
TYPE emp_cursor_type IS REF CURSOR RETURN employees%ROWTYPE;
emp_cursor emp_cursor_type;
RETURN employees%ROWTYPE specifies
BEGIN that the cursor variable will reference a result
-- Your PL/SQL code here set with the same structure as the employees
table.
END;
Note: You can then use this emp_cursor cursor variable to dynamically assign SQL statements and work
with the result sets.
1
3
Cursors and Exception Handling
1
4
Cursors and Exception Handling
cur %FOUND Returns TRUE if the last FETCH found a row Were Any Rows Affected?
cur %NOTFOUND Returns FALSE if the last FETCH found a Were No Rows Affected?
row
cur %ISOPEN Returns TRUE if the specified cursor is Is the Cursor Open?
open
cur %ROWCOUNT Returns the number of rows modified by How Many Rows Were Affected?
the DML statement
SQL Returns the number of rows processed for
%BULK_ROWCOU each execution of the bulk DML operation
NT
1
5
Cursors and Exception Handling
1
6
Cursors and Exception Handling
BEGIN END;
1
7
Cursors and Exception Handling
BEGIN
-- Perform bulk update using FORALL
FORALL i IN 1..emp_ids.COUNT
UPDATE employees
SET salary = salary * 1.05
WHERE employee_id = emp_ids(i);
COMMIT;
DBMS_OUTPUT.PUT_LINE('Bulk update completed.');
END;
/
1
8
Cursors and Exception Handling
1
9
Cursors and Exception Handling
b) Exception Handling
• To catch and process exceptions.
• Handlers specify what actions to take when a specific exception occurs.
• Handlers can be defined at various levels, including within a specific block or at the outermost level of
your PL/SQL code.
BEGIN
EXCEPTION
WHEN custom_exception THEN
-- Handle the custom exception
WHEN OTHERS THEN
-- Handle other unanticipated exceptions
END;
2
0
Cursors and Exception Handling
c) Raising Exceptions:
• Use the RAISE statement to explicitly raise an exception within your PL/SQL code.
• It is useful for custom error handling or for re-raising exceptions with additional context.
IF some_condition THEN
RAISE custom_exception;
END IF;
2
1
Cursors and Exception Handling
2
2
Cursors and Exception Handling
e) User-Defined Exceptions:
• Are addition to built-in exceptions
• you can define your custom exceptions using the EXCEPTION keyword.
• It allows you to create meaningful error messages and handle specific conditions in your code.
• It’s including NO_DATA_FOUND and TOO_MANY_ROWS, which are raised by Oracle automatically
under specific conditions. You can catch and handle these exceptions as needed.
2
3
Cursors and Exception Handling
• You can customize exception messages by creating your own user-defined exceptions and associating
them with custom error messages.
• It allows you to provide more meaningful and informative error messages to users or developers
when an exception is raised.
Decla ed
sectio EPTION
excep
the D
DECLARE
the E ord.
defin
re use
keyw
custom_exception EXCEPTION;
tions
n by u
ECLAR g
XC
BEGIN
r-
i n
si n
E
...
EXCEPTION
WHEN custom_exception THEN
-- Handle the custom exception
...
END;
2
5
Cursors and Exception Handling
-- us n w ror
BEGIN
Ra tom it
ex cust ssag cod
i s t he e
rror
c
i se
ce om e a e
pt
IF some_condition THEN code
th
i o er n d
m rror
e
e
RAISE_APPLICATION_ERROR(-20001, 'This is a custom error message.');
ha
END IF;
EXCEPTION
WHEN custom_exception THEN
-- Handle the custom exception
END;
2
6
W
ex hen
yo cep yo
ac ur tio u c
us ces EXC n u atc
wh ing s th EPT sing h a
as ich the e c IO a cus
ra soc re SQ ust N se WH tom
is e i a t u L E o m c E N
d ted rns RR e tion cl
ex w t M rr
ce it he o , y au
pti h t e fun r m ou se in
on he rro cti es can
. m r m o n s ag
os e , e
t r ssa
ec ge
en
t ly
...
END;
BEGIN
EXCEPTION
WHEN custom_exception THEN
age
mess r
erro m
usto
-- Handle the custom exception and display the custom error message
Customize PL/SQL exception messages: Handling Custom Exceptions:
the c isplay
7
2
d
Cursors and Exception Handling
and rieve
t
to re sed
It is u
Cursors and Exception Handling
2
8
Cursors and Exception Handling
E RS en BEGIN
H h
OT ed w fic -- Your PL/SQL code here
N r i
HE igge spec ed in EXCEPTION
h e W is tr the efin the .
T e of h
u s e n s d atc rred WHEN OTHERS THEN
cla non ptio de m occu -- Handle the unanticipated error here
ce o t
ex ur c tha DBMS_OUTPUT.PUT_LINE('An unanticipated error occurred.');
yo rror
e END;
2
9
Cursors and Exception Handling
3
0
Cursors and Exception Handling
3
1
Cursors and Exception Handling
3
2
Cursors and Exception Handling
The End…
3
3