0% found this document useful (0 votes)
17 views48 pages

Business Analysis Chap04 Notes

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)
17 views48 pages

Business Analysis Chap04 Notes

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

Chapter 4

Cursors and
Exception handling
Objectives
• At the end of this lesson, you must be able to:
• Manipulate data with cursors
• Use bulk processing features
• Manage errors with exception handlers
• Construct user-defined exception handlers
• Customize PL/SQL exception messages
• Trap unanticipated errors
Manipulate data with cursors
• Oracle creates a memory area, known as the context area, for
processing an SQL statement, which contains all the information
needed for processing the statement; for example, the number of
rows processed, etc.
• A cursor is a pointer to this context area. PL/SQL controls the context
area through a cursor. A cursor holds the rows (one or more) returned
by a SQL statement. The set of rows the cursor holds is referred to as
the active set.
Manipulate data with cursors (Cont.)
• You can name a cursor so that it could be referred to in a program to
fetch and process the rows returned by the SQL statement, one at a
time. There are two types of cursors −
• Implicit cursors
• Explicit cursors
• Implicit Cursors
• Implicit cursors are automatically created by Oracle whenever an SQL
statement is executed, when there is no explicit cursor for the
statement. Programmers cannot control the implicit cursors and the
information in it.
Manipulate data with cursors (Cont.)
• Whenever a DML statement (INSERT, UPDATE and DELETE) is issued,
an implicit cursor is associated with this statement. For INSERT
operations, the cursor holds the data that needs to be inserted. For
UPDATE and DELETE operations, the cursor identifies the rows that
would be affected.
• In PL/SQL, you can refer to the most recent implicit cursor as the SQL
cursor, which always has attributes such as %FOUND, %ISOPEN,
%NOTFOUND, and %ROWCOUNT. The SQL cursor has additional
attributes, %BULK_ROWCOUNT and %BULK_EXCEPTIONS, designed
for use with the FORALL statement. The following table provides the
description of the most used attributes −
Manipulate data with cursors (Cont.)
Manipulate data with cursors (Cont.)
• Any SQL cursor attribute will be accessed as sql%attribute_name as
shown below in the example.
Manipulate data with cursors (Cont.)
• The following program will update the table and increase the salary of
each customer by 500 and use the SQL%ROWCOUNT attribute to
determine the number of rows affected −
Manipulate data with cursors (Cont.)
• When the above code is executed at the SQL prompt, it produces the
following result −
Manipulate data with cursors (Cont.)
• If you check the records in customers table, you will find that the rows
have been updated −
Manipulate data with cursors (Cont.)
• Explicit Cursors
• Explicit cursors are programmer-defined cursors for gaining more
control over the context area. An explicit cursor should be defined in
the declaration section of the PL/SQL Block. It is created on a SELECT
Statement which returns more than one row.
• The syntax for creating an explicit cursor is −
Manipulate data with cursors (Cont.)
• Working with an explicit cursor includes the following steps −
Manipulate data with cursors (Cont.)
Manipulate data with cursors (Cont.)
• Declaring the Cursor
• Declaring the cursor defines the cursor with a name and the
associated SELECT statement. For example −
Manipulate data with cursors (Cont.)
• Opening the Cursor
• Opening the cursor allocates the memory for the cursor and makes it
ready for fetching the rows returned by the SQL statement into it. For
example, we will open the above defined cursor as follows −
Manipulate data with cursors (Cont.)
• Fetching the Cursor
• Fetching the cursor involves accessing one row at a time. For example,
we will fetch rows from the above-opened cursor as follows −
Manipulate data with cursors (Cont.)
• Closing the Cursor
• Closing the cursor means releasing the allocated memory. For
example, we will close the above-opened cursor as follows −
Manipulate data with cursors (Cont.)
• Example
Manipulate data with cursors (Cont.)
• Variable Declarations:

c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;

• These lines declare three variables: c_id, c_name, and c_addr. The
data types of these variables are inferred from the corresponding
columns (id, name, and address) in the customers table using the
%type attribute.
Manipulate data with cursors (Cont.)
• CURSOR Declaration:

CURSOR c_customers IS
SELECT id, name, address FROM customers;

• A cursor named c_customers is declared. It defines a result set that


retrieves data from the customers table, specifically the id, name, and
address columns.
Manipulate data with cursors (Cont.)
• OPEN Cursor:

OPEN c_customers;
• This line opens the cursor c_customers, making it ready to fetch rows
from the result set.
• LOOP
• This begins a loop, which will continue to fetch and process rows from
the cursor until a specific condition is met.
Manipulate data with cursors (Cont.)
• FETCH Cursor Into Variables:

FETCH c_customers into c_id, c_name, c_addr;


• Inside the loop, this line fetches the next row from the
cursor c_customers into the variables c_id, c_name,
and c_addr. It populates these variables with the
values from the current row.
Manipulate data with cursors (Cont.)
• EXIT WHEN Condition:
EXIT WHEN c_customers%NOTFOUND;
• This line checks if there are no more rows to fetch in the cursor (c_customers).
If there are no more rows, it exits the loop.
• Print Data:
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
• Within the loop, this line prints the values of c_id, c_name, and c_addr
concatenated together with spaces to the output. This effectively prints the
data from each row in the customers table.
• END LOOP:
• This marks the end of the loop.
Manipulate data with cursors (Cont.)
• CLOSE Cursor:
CLOSE c_customers;
• After processing all rows, this line closes the cursor to release
associated resources.
• Summary
• in summary, this PL/SQL code declares variables, opens a cursor, fetches
data from a table, prints the data, and then closes the cursor after
processing all rows. It's essentially a way to retrieve and display the
contents of the customers table.
Manipulate data with cursors (Cont.)
• Output of the above example:
Manipulate data with cursors (Cont.)
• Example 2
• In this example, we are going to see how to declare, open, fetch and
close the explicit cursor.
• Refere to chapter 3 for the emp table
• We will project all the employee’s name from emp table using a
cursor. We will also use cursor attribute to set the loop to fetch all the
record from the cursor.
Manipulate data with cursors (Cont.)
Manipulate data with cursors (Cont.)
• Code Explanation
• Code line 2: Declaring the cursor guru99_det for statement ‘SELECT emp_name FROM emp’.
• Code line 3: Declaring variable lv_emp_name.
• Code line 5: Opening the cursor guru99_det.
• Code line 6: Setting the Basic loop statement to fetch all the records in the ’emp’ table.
• Code line 7: Fetches the guru99_det data and assign the value to lv_emp_name.
• Code line 9: Using the cursor attribute ‘%NOTFOUND’ to find whether all the record in the cursor is
fetched. If fetched then it will return ‘TRUE’ and control will exit from the loop, else the control will keep
on fetching the data from the cursor and print the data.
• Code line 11: EXIT condition for the loop statement.
• Code line 12: Print the fetched employee name.
• Code line 14: Using the cursor attribute ‘%ROWCOUNT’ to find the total number of records that got
affected/fetched in the cursor.
• Code line 15: After exiting from the loop the cursor is closed and the memory allocated is set free.
Use bulk processing features

• In PL/SQL, the term "bulk processing" refers to techniques that allow


you to minimize the number of context switches between the PL/SQL
and SQL engines, and thereby increase performance, especially when
dealing with large amounts of data.
• Oracle PL/SQL provides the functionality of fetching the records in
bulk rather than fetching one-by-one.
• This BULK COLLECT can be used in ‘SELECT’ statement to populate the
records in bulk or in fetching the cursor in bulk.
• Since the BULK COLLECT fetches the record in BULK, the INTO clause
should always contain a collection type variable.
Use bulk processing features (Cont.)
• The main advantage of using BULK COLLECT is it increases the
performance by reducing the interaction between database and
PL/SQL engine.
• Syntax:
Use bulk processing features (Cont.)
• FORALL Clause
• The FORALL allows to perform the DML operations on data in bulk. It
is similar to that of FOR loop statement except in FOR loop things
happen at the record-level whereas in FORALL there is no LOOP
concept. Instead, the entire data present in the given range is
processed at the same time.
• Syntax:
Use bulk processing features (Cont.)
• LIMIT Clause
• The bulk collect concept loads the entire data into the target collection variable as a
bulk i.e. the whole data will be populated into the collection variable in a single-go.
But this is not advisable when the total record that needs to be loaded is very large,
because when PL/SQL tries to load the entire data it consumes more session memory.
Hence, it is always good to limit the size of this bulk collect operation.

• However, this size limit can be easily achieved by introducing the ROWNUM condition
in the ‘SELECT’ statement, whereas in the case of cursor this is not possible.

• To overcome this Oracle has provided ‘LIMIT’ clause that defines the number of
records that needs to be included in the bulk.
Use bulk processing features (Cont.)
• Syntax:

• In the above syntax, the cursor fetch statement uses BULK COLLECT
statement along with the LIMIT clause.
Use bulk processing features (Cont.)
• BULK COLLECT Attributes
• Similar to cursor attributes BULK COLLECT has %BULK_ROWCOUNT(n)
that returns the number of rows affected in the nth DML statement of
the FORALL statement, i.e. it will give the count of records affected in
the FORALL statement for every single value from the collection
variable. The term ‘n’ indicates the sequence of value in the
collection, for which the row count is needed.
Use bulk processing features (Cont.)
• Example 1: In this example, we will project all the employee name
from emp table using BULK COLLECT and we are also going to
increase the salary of all the employees by 5000 using FORALL.
Use bulk processing features (Cont.)
Use bulk processing features (Cont.)
• Output
Use bulk processing features (Cont.)
• Code Explanation:

• Code line 2: Declaring the cursor guru99_det for statement ‘SELECT emp_name FROM
emp’.
• Code line 3: Declaring lv_emp_name_tbl as table type of VARCHAR2(50)
• Code line 4: Declaring lv_emp_name as lv_emp_name_tbl type.
• Code line 6: Opening the cursor.
• Code line 7: Fetching the cursor using BULK COLLECT with the LIMIT size as 5000 intl
lv_emp_name variable.
• Code line 8-11: Setting up FOR loop to print all the record in the collection lv_emp_name.
• Code line 12: Using FORALL updating the salary of all the employee by 5000.
• Code line 14: Committing the transaction.
Use bulk processing features (Cont.)
• **SAVE EXCEPTIONS with FORALL**:
• If you expect that some of the DML operations might fail (e.g.,
because of a constraint violation), you can use the `SAVE EXCEPTIONS`
clause. It will continue processing after an exception and will collect
the exceptions to be handled after the `FORALL` completes.
• These features can significantly speed up operations that affect many
rows, making them essential tools for optimizing PL/SQL code.
Exception handlers
• An exception is an error condition during a program execution.
PL/SQL supports programmers to catch such conditions using
EXCEPTION block in the program and an appropriate action is taken
against the error condition. There are two types of exceptions −
Exception handlers(Cont.)
• Syntax for Exception Handling
• The general syntax for exception handling is as follows. Here you can
list down as many exceptions as you can handle. The default
exception will be handled using WHEN others THEN −
Exception handlers(Cont.)
• Example: using the CUSTOMERS table
Exception handlers (Cont.)
• When the above code is executed at the SQL prompt, it produces the
following result −

• The above program displays the name and address of a customer


whose ID is given. Since there is no customer with ID value 8 in our
database, the program raises the run-time exception
NO_DATA_FOUND, which is captured in the EXCEPTION block.
Exception handlers (Cont.)
• Raising Exceptions
• Exceptions are raised by the database server automatically whenever
there is any internal database error, but exceptions can be raised
explicitly by the programmer by using the command RAISE. Following
is the simple syntax for raising an exception −
Exception handling (Cont.)
• User-defined Exceptions
• PL/SQL allows you to define your own exceptions according to the
need of your program. A user-defined exception must be declared and
then raised explicitly, using either a RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
• The syntax for declaring an exception is −
Exception handling (Cont.)
• Example
• The following example illustrates the concept. This program asks for a customer
ID, when the user enters an invalid ID, the exception invalid_id is raised.
Exception handling (Cont.)
• When the above code is executed at the SQL prompt, it produces the
following result −
Source
• https://www.tutorialspoint.com/plsql/index.htm
• https://www.geeksforgeeks.org/plsql-introduction/
• https://www.guru99.com/pl-sql-tutorials.html

You might also like