0% found this document useful (0 votes)
19 views33 pages

WEEK 4 - Chapter 4 Cursors and Exception Handling

Uploaded by

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

WEEK 4 - Chapter 4 Cursors and Exception Handling

Uploaded by

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

AIBYP2A

BUSINESS ANALYSIS 2.2 (PL/SQL)

www.vut.ac.za
Vivian Mapande
1
www.vut.ac.za

CONTENTS
1. Manipulate data with cursors

2. Use bulk processing features

3. Manage errors with exception handlers

4. Construct user-defined exception handlers

5. Customize PL/SQL exception messages

6. Trap unanticipated errors


2

The contents of this presentation is confidential. ©VUT


Cursors and Exception Handling

Manipulate data with cursors


• When you execute a SQL statement from PL/SQL, the Oracle database assigns a
private work area for that statement.

• 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

Manipulate data with cursors(Cont.)


Working with cursors includes:
• A cursor is a pointer to the results of a query run against one or more tables in the
database.
For example, the following cursor declaration associates the entire employee table
with the cursor named employee_cur:

CURSOR employee_cur IS SELECT * FROM employee;


--Once I have declared the cursor, I can open it
OPEN employee_cur;
--Then I can fetch rows from it
FETCH employee_cur INTO employee_rec;
--Finally, I can close the cursor
CLOSE employee_cur;

4
Cursors and Exception Handling

Manipulate data with cursors(Cont.)

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

Manipulate data with cursors(Cont.)

Example of Implicit cursors -- Display the retrieved data


DECLARE
DBMS_OUTPUT.PUT_LINE('Employee Name: ' || v_emp_name);
v_emp_name employees.first_name%TYPE;
DBMS_OUTPUT.PUT_LINE('Employee Salary: ' || v_emp_salary);
v_emp_salary employees.salary%TYPE;
END;
BEGIN
/
-- Select a specific employee's name and salary

SELECT first_name, salary

INTO v_emp_name, v_emp_salary

FROM employees

WHERE employee_id = 101;

6
Cursors and Exception Handling

Manipulate data with cursors(Cont.)


2. Explicit cursors

• 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.

• Are explicitly declared, opened, fetched, and closed by the developer.

• 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

Manipulate data with cursors(Cont.)

• 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

Manipulate data with cursors(Cont.)


Explicit cursor syntax:

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

Manipulate data with cursors(Cont.)


3. Cursor variables
• Are also known as REF CURSORs, are a special type of cursor in PL/SQL that
allow you to create dynamic and reusable queries
• They are not tied to a specific SQL statement.
• They are defined as a reference to a result set, and you can assign various SQL
statements to them at runtime.

Key characteristics and advantages of cursor variables in PL/SQL:


• Dynamic Queries
• Cursor variables allow you to build SQL queries dynamically based on runtime
conditions.
• This flexibility is valuable when you need to construct and execute different
queries based on user input or changing requirements.

1
0
Cursors and Exception Handling

Manipulate data with cursors (Cont.)


• Parameterized Queries
• You can define cursor variables with parameters, which enables you to create reusable
queries with placeholders.
• Its useful when you want to pass parameters to a query to filter or customize the result
set.
• Reduced Code Duplication
• You can reduce code duplication because you can define a single cursor variable and
reuse it with different SQL statements, avoiding the need to create multiple explicit
cursors for similar purposes.
• Dynamic Result Sets
• Cursor variables allow you to work with result sets that may change in structure at
runtime, making them suitable for scenarios where the column list of the result set is not
known in advance.
• Better Abstraction
• They provide a higher level of abstraction, making code more readable and
maintainable, especially when dealing with complex and variable queries.

1
1
Cursors and Exception Handling

Manipulate data with cursors (Cont.)


Cursor Variable Syntax

cursor_variable_type:This REF CURSOR:This is the


is the user-defined type that user-defined type that
represents the cursor represents the cursor variable.
variable. You can give it a You can give it a meaningful
meaningful name that name that reflects its purpose.
reflects its purpose.

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.

RETURN:This part is optional. If


you want to specify the data type
of the result set that the cursor
variable will reference, you can
use the RETURN clause.

1
2
Cursors and Exception Handling

Manipulate data with cursors (Cont.)


Cursor Variable Syntax

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

Manipulate data with cursors (Cont.)


4. Cursor attributes
• Are properties associated with cursors in PL/SQL that provide information about the state of a
cursor.
• They can be used to check the status of a cursor during its lifecycle.
• Some common cursor attributes in PL/SQL include:
• ‘%FOUND’: Checks if a FETCH statement successfully retrieved a row.
• Syntax: cursor_name%FOUND
• ‘%NOTFOUND’: Checks if a FETCH statement did not retrieve a row.
• Syntax: cursor_name%NOTFOUND
• ‘%ROWCOUNT’: Returns the number of rows fetched from the cursor.
• Syntax: cursor_name%ROWCOUNT
• ‘%ISOPEN’: Checks if a cursor is currently open.
• Syntax: cursor_name%ISOPEN

1
4
Cursors and Exception Handling

Manipulate data with cursors (Cont.)


Cursor attributes comparison

Cursor Attribute Effect Guidelines

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

Use bulk processing features


• Bulk processing in PL/SQL allows you to work with multiple rows of data at once.
• It is often more efficient than processing one row at a time.
• It's especially useful when dealing with large datasets.
• There are two main bulk processing features in PL/SQL:
a) BULK COLLECT
• BULK COLLECT is used to fetch multiple rows from a query into collections (arrays or nested
tables) in a single database round-trip.
a) FORALL
• FORALL is used to perform bulk DML (Data Manipulation Language) operations, such as inserts,
updates, and deletes, on collections in a single database round-trip.

1
6
Cursors and Exception Handling

Use bulk processing features-Bulk collect


DECLARE -- Process the data in the collections

TYPE emp_id_list IS TABLE OF NUMBER; FOR i IN 1..emp_ids.COUNT LOOP

TYPE emp_name_list IS TABLE OF VARCHAR2(50); DBMS_OUTPUT.PUT_LINE('Employee ID: '

emp_ids emp_id_list; || emp_ids(i) || ', Name: ' || emp_names(i));

emp_names emp_name_list; END LOOP;

BEGIN END;

-- Fetch multiple rows into collections /

SELECT employee_id, first_name


BULK COLLECT INTO emp_ids, emp_names
FROM employees
WHERE department_id = 30;

1
7
Cursors and Exception Handling

Use bulk processing features-ForAll


DECLARE
TYPE emp_id_list IS TABLE OF NUMBER;
emp_ids emp_id_list := emp_id_list(101, 102, 103); -- Example employee IDs to update

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

Manage errors with exception handlers (Cont.)


• Exception handling is a critical aspect of PL/SQL programming that allows you to manage errors and
exceptions that may occur during the execution of your code.
• General overview of how to manage errors with exception handlers in PL/SQL:
a) Exception Declaration:
• you need to declare them first.
• You can declare exceptions using the DECLARE section of your PL/SQL block
• Assign a name and optionally associating it with an Oracle error code or a user-defined error code.
DECLARE
custom_exception EXCEPTION;
...
BEGIN
...
EXCEPTION
WHEN custom_exception THEN
-- Handle the custom exception
...
END;

1
9
Cursors and Exception Handling

Manage errors with exception handlers (Cont.)

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

Manage errors with exception handlers (Cont.)

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

Manage errors with exception handlers (Cont.)

d) Nested Exception Handling:


• PL/SQL allows you to nest blocks with their own exception handlers.
• If an exception is not handled in an inner block, it spreads to the outer block's exception section. This
allows for more granular handling of errors.
BEGIN
... EXCEPTION
BEGIN WHEN outer_exception THEN
... -- Handle the outer exception
EXCEPTION ...
WHEN inner_exception THEN END;
-- Handle the inner exception
END;

2
2
Cursors and Exception Handling

Manage errors with exception handlers (Cont.)

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.

Handling Built-in Exceptions:

• 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

Manage errors with exception handlers (Cont.)


IF v_value = 0 THEN
e) User-Defined Exceptions:
RAISE custom_exception;
DECLARE
END IF;
custom_exception EXCEPTION;
v_value NUMBER := 0;
EXCEPTION
BEGIN
WHEN custom_exception THEN
-- Attempt to divide by zero
-- Handle the custom exception
BEGIN
DBMS_OUTPUT.PUT_LINE('Custom exception
v_value := 10 / 0;
raised');
EXCEPTION
WHEN OTHERS THEN
WHEN ZERO_DIVIDE THEN
-- Handle other unanticipated exceptions
-- Handle division by zero
DBMS_OUTPUT.PUT_LINE('An error occurred');
DBMS_OUTPUT.PUT_LINE('Division by
END;
zero');
/
END; 2
4
Cursors and Exception Handling

Customize PL/SQL exception messages: Declare User-Defined Exceptions

• 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

Customize PL/SQL exception messages: Assign Custom Error Messages


• To associate custom error messages with your user-defined exceptions, you can use the
RAISE_APPLICATION_ERROR procedure.
• It allows you to raise an exception with a custom error message and an error code.
DECLARE
custom_exception EXCEPTION;

-- 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

DBMS_OUTPUT.PUT_LINE('Custom Exception: ' || SQLERRM);

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

Trap unanticipated errors


• Unanticipated errors are unexpected issues that may occur during program execution
• They need to be handled gracefully to prevent application crashes or data corruption
• Steps to trap unanticipated errors in PL/SQL:
a) Use EXCEPTION Handlers:
• Use EXCEPTION handlers to catch and handle unanticipated errors.
b) Handle the GENERIC Exception:
• Generic exception handler Its included so that it can catch any unanticipated errors.
• It is done using the WHEN OTHERS clause.

2
8
Cursors and Exception Handling

Trap unanticipated errors(Cont.)

Handle the GENERIC Exception example:

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

Trap unanticipated errors(Cont.)

c) Capture Error Information:


• To better understand and diagnose the unanticipated error, you can capture error information using the
SQLCODE and SQLERRM functions.
• These functions provide the error code and error message, respectively.
BEGIN
-- Your PL/SQL code here
EXCEPTION
WHEN OTHERS THEN
-- Capture error information
DBMS_OUTPUT.PUT_LINE('Error Code: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('Error Message: ' || SQLERRM);
END;

3
0
Cursors and Exception Handling

Trap unanticipated errors(Cont.)

d) Logging and Notification:


• Depending on the severity of the error, you can log the error details in a dedicated error log table
• Send notifications to administrators or take other appropriate actions to handle the error.
BEGIN
-- Your PL/SQL code here
EXCEPTION
WHEN OTHERS THEN
-- Log error details to an error log table
INSERT INTO error_log (error_code, error_message, error_timestamp)
VALUES (SQLCODE, SQLERRM, SYSTIMESTAMP);
-- Notify administrators via email or other means
send_notification('Error occurred in PL/SQL code.');
END;

3
1
Cursors and Exception Handling

Trap unanticipated errors(Cont.)

Reraise the Exception (Optional):


• You may want to reraise the unanticipated exception after capturing the error information.
• This allows higher-level exception handlers to further process or log the error.
BEGIN
-- Your PL/SQL code here
EXCEPTION
WHEN OTHERS THEN
-- Capture error information
DBMS_OUTPUT.PUT_LINE('Error Code: ' || SQLCODE);
DBMS_OUTPUT.PUT_LINE('Error Message: ' || SQLERRM);
-- Reraise the exception
RAISE;
END;

3
2
Cursors and Exception Handling

The End…

3
3

You might also like