Return to Controlling Explicit Cursors Open the Cursor Pointer Ea " = Cursor Fetch a Row from the Cursor... Controlling Explicit Cursors continued PARR Reem ee Rete Hae e OEE RARE
Trang 2* Declare and explain explicit cursors to fetch rows
from the database
* Create an explicit cursor with parameters
¢ Write cursor FOR loops
24-2 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Trang 3
Objectives
ee eee ee eee ee eee ee cee eee eee eee ee ee eee eee ee eee ee eee cere eee eee eee ee eee eee eee eee eee eee eee eee eee eee
You may need to use a multiple row SELECT statement within PL/SQL to
process many rows To accomplish this, you declare and control explicit cursors, which are used in loops, including the cursor FOR loop
At the end of this lesson, you should be able to
e Explain the difference between implicit and explicit cursors
e Declare and use explicit cursors to fetch rows from the database
e Create an explicit cursor containing parameters
e Write cursor FOR loops
Processing Queries by Using Explicit Cursors 24-3
Trang 4ORACLE’
i ee eee ee eee eee eee eee cee eee eee eee eee ee eee eee ee ee ee eee ee ee ee ee eee eee eee eee 6e
What Is a Cursor?
* Every SQL statement executed by the Oracle7 Server
has an individual cursor associated with it
Explicit Cursor Functions
* Process beyond the first row returned by the query, row by row
se Keep track of which row is currently being processed
¢ Control cursors manually in the PL/SQL block
Trang 5Overview
The Oracle7 Server uses work areas called “‘private SQL areas” to execute SQL
statements and store processing information PL/SQL cursors let you name a private SQL area and access its stored information The cursor directs all phases of
processing
Cursor Type Description
Implicit Declared by PL/SQL implicitly for all DML and PL/SQL
SELECT statements
Explicit Declared and named by the programmer and manipulated
through specific statements within the block’s executable actions
Recall that the SELECT statement in PL/SQL must only return a single row PL/SQL actually attempts to fetch two rows from an implicit cursor: one to satisfy the query, and a second to see if further rows were returned One method to eliminate this extra fetch is to use an explicit cursor
Explicit Cursor Functions
e Can process beyond the first row returned by the query, row by row
e Keep track of which row is currently being processed
e Allow the programmer to manually control them in the PL/SQL block
Processing Queries by Using Explicit Cursors 24-5
Trang 6DECLARE 3 OPEN [| -| FETCH CLOSE
* Create a * Identify the * Load the * Test for * Release the
named SQL active set current row existing rows _ active set
area into variables = Return to
Controlling Explicit Cursors
Open the Cursor
Pointer
Ea
"
= Cursor
Fetch a Row from the Cursor
Trang 7Controlling Explicit Cursors
THEO MMe meee ee eee aero dames meen eee ere ere eee Ee DRED SO OHE EERE EEE EEE EH EEE ED TEE EOOH DOES ESHOP DEED EODODDDEDAE SEER OOO DOSE EEE EED
Now that you have a conceptual understanding of cursors, review the steps to use them The syntax for each step follows on the next pages
Controlling Explicit Cursors Using Four Commands
1 Declare the cursor
Declare the cursor by naming it and defining the structure of the query to be performed within it
2 Open the cursor
The OPEN statement executes the query and binds any variables that are
referenced Rows identified by the query are called the active set and are now available for fetching
3 Fetch data from the cursor
The FETCH statement loads the current row from the cursor into variables Each fetch causes the cursor to move its pointer to the next row in the active set
Therefore, each fetch will access a different row returned by the query
In the flow diagram on the left page, each fetch tests the cursor for any existing rows If rows are found, it loads the current row into variables, else it closes the
cursor
4 Close the cursor
The CLOSE statement releases the active set of rows It is now possible to reopen
the cursor to establish a fresh active set
nee meee eee emer tHe OREO ERE e eee EERE EOE OH OED aE DEE SES
—— _ DŨỤŨỤỘŨDỘDŨ
Processing Queries by Using Explicit Cursors 24-7
Trang 8ORACLE’
eee meee eee ree eee ee A HEE EERE EERE SEEDED EEE DDE OE REEDED SHEER EE EE HEED HS ECE ESEEEE HEH ETHERS HS OD ESR EHO HT EHD HEED DO RED
Declaring the Cursor: Syntax
'* Define parameters to allow substitution of values
into the cursor query
DECLARE CURSOR cursor_name IS
Declaring the Cursor: Example
Retrieve the line items of an order one by one
DECLARE
v_ord id s_item.ord id%TYPE;
v_product_id s_item.product_id%TYPE;
v item total NUMBER (11,2);
CURSOR item cursor IS
SELECT product_id, price*quantity
FROM s_item WHERE ord_id = v_ord_ id;
Trang 9Controlling Explicit Cursors continued
PARR Reem ee Rete Hae e OEE RARE HERDED EEO ERED EDEL SERS SEOE SDE EHHESESED ESOS SEES EEEHESEHESH HOE E SEES SHE HHA DSESEEEHODT OED
Declaring the Cursor
Use the CURSOR statement to declare an explicit cursor You can define parameters
to allow substitution of values into the query when the cursor is opened You can also reference variables within the query, but you must declare them before the cursor
where: cursor_name is a PL/SQL identifier
Select_statement is a SELECT statement without an INTO
clause
Note: Do not include the INTO clause within the cursor declaration because it
appears later within the FETCH statement
Processing Queries by Using Explicit Cursors 24-9
Trang 10ORACLE’
TAO m ee emcee da were mera emer erence eH es OO RHO EE EO EDR ESE EOE MS AE HSE SOU HSE EOEES HEED EEE ORE RHEE ERED EES EOE REECE RHEE EE EEO ONES ERE eeeEn
Opening the Cursor: Syntax
¢ Open the cursor to execute the query and © identify the active set
eee ee eee eee eee eee eee eee eee ere eee eee Lee eee ee ee ee Teer eee ee Se eee eee eee eee TL Se CeCe ere rer ee ee eee Teer Seer ee er Te eee eee ee eee eee eee eee 2 0306
24-10 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Trang 11Controlling Explicit Cursors continued
hee eee ee eee eee eee ee ee ee eee eee ee eee Cee Eee SoC eC eee ee eee eee eee ee eT ee ee eee ee ee ee ee ee ee ee ee es
Opening the Cursor
Open the cursor to execute the query and identify the active set after specifying
values for all input variables The cursor will now point to the first row in the active set
an exception However, you can test the cursor’s status after a fetch
Processing Queries by Using Explicit Cursors 24-11
Trang 12ORACLE’
he ee ee ee eee ee eee ee ee eee eee eee ee ee eee eee ee eee eee See ee eee eee eee eee ee Tee eee eee eee eee eee ee
Fetching Data from the Cursor: Syntax
* Retrieve the current row values into output variables
* Include the same number of variables
¢ Match each variable to correspond to the columns
Fetching Data from the Cursor: Example
Retrieve the line items of an order one-by-one
Trang 13Controlling Explicit Cursors continued
TROP e eee w nema e rman emer e cera ee eens rae HEae See Eee Resa AEE SHEE EHE EHO R ES EEE HHT E RSH E SHOES ETH D ES OEE EER EOORE SHEE ESSE REESE ESSE OEE ERED
Fetching Data from the Cursor
Use the FETCH statement to retrieve the current row values into output variables After the fetch, you can manipulate the variables by further statements
where: cursor name is the name of the previously declared cursor
variable is an output variable to store the results
Guidelines
e Include the same number of variables within the INTO clause of the FETCH statement as output columns in the SELECT statement, and be sure that the
datatypes are compatible
e Match each variable to correspond to the columns positionally
e Alternatively, define a record for the cursor and reference the record in the
FETCH INTO clause
e Test to see if the cursor contains rows If a fetch acquires no values, that is, there are now rows left to process in the active set and no error is recorded
Processing Queries by Using Explicit Cursors 24-13
Trang 14ORACLE’
CUO m eee med ae em eee see eee ee meee Ree ee Hee HEE EEE ROME DEES OEE REE HOE OR OH EEER AHA R EE EES EOE E HEHE ESOS REEHE HHO EEO ED OLED EEE OSES
Closing the Cursor: Syntax
* Close the cursor after completing the processing
of the rows
CLOSE cursor name;
* Reopen the cursor again, if required
* Do not attempt to fetch data from a cursor once
it has been closed
24-14 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Trang 15
Controlling Explicit Cursors continued
Z5 ˆỐÖ-FˆˆỄŠˆỐÓ_ˆÓŠ .Ẻ Ô.Ô.Ố Ắ.Ố
Closing the Cursor
Close the cursor after completing the processing of the SELECT statement This step allows the cursor to be reopened, if required Therefore, you can establish an active set several times
where: cursor_name is the name of the previously declared cursor
Note: Do not attempt to fetch data from a cursor once it has been closed or the
INVALID_CURSOR exception will be raised
xỒ -
Processing Queries by Using Explicit Cursors 24-15
Trang 16ORACLE’
tỎỔỐỐ
Explicit Cursor Attributes
Obtain status information about a cursor by using
Attribute Type Description
%ISOPEN Boolean Evaluates to TRUE if the cursor is
open
%NOTFOUND Boolean Evaluates to TRUE if the most
recent fetch does not return a row
%FOUND Boolean Evaluates to TRUE until the
most recent fetch does not return a row
rows returned so far
Controlling Multiple Fetches
¢ Process several rows from an explicit cursor using a loop
¢ Fetch arow with each iteration
¢ Write atest for an unsuccessful fetch by using the %NOTFOUND attribute
¢ Test success of each fetch using explicit cursor attributes
24-16 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder
Trang 17Explicit Cursor Attributes
Á ĐÓ 9 dỌ lo In ĐO Đo CĐ ÓC eee ORE HEH ER EHH D Eee e HEED on 9 SEED FEES HEHE EHS E SETTER TEES ODEO DH OHEHEEOD SORES EES OSES DEH EE ET OES EN EOE
As with implicit cursors, there are four attributes for obtaining status information about a cursor When used, the attribute name is preceded by the cursor identifier
Cursor Attribute Description
%ISOPEN Boolean attribute that evaluates to TRUE if the cursor is
open
%NOTFOUND Boolean attribute that evaluates to TRUE if the most recent
fetch does not return a row
%FOUND Boolean attribute that evaluates to TRUE until the most
recent fetch does not return a row; complement of
%NOTFOUND
%ROWCOUNT Numeric attribute that evaluates to the total number of rows
retumed so far
Note: Do not reference cursor attributes directly within a SQL statement
Controlling Multiple Fetches from Explicit Cursors
Typically, when you want to process several rows from an explicit cursor, you define
a loop to perform a fetch on each iteration Eventually, all rows in the active set will
be processed, and an unsuccessful fetch sets the %7 NOTFOUND attribute to TRUE Use the explicit cursor attributes to test success of each fetch before any further
references are made to the cursor If you omit an exit criteria, an infinite loop will result
\ For more information, see
iG PL/SQL User’s Guide and Reference, Release 2.3 “Using Cursor Attributes” section
Processing Queries by Using Explicit Cursors 24-17
Trang 18ORACLE’
eee eee eee eee eee eee eee eee ee eee eee eee eee ee ee eee eee eT eee ee ee eee eee eee Ce eee Cee EEE Sere Cee Eee eee ee eee eee eee ees
The %ISOPEN Attribute: Example
¢ Fetch rows only when the cursor is open
* Test if the cursor is open using %ISOPEN cursor
attribute before performing a fetch
IF item_cursortISOPEN THEN FETCH item_cursor INTO v_quantity, v_price;
The %NOTFOUND and %ROWCOUNT
Attributes: Example
¢ Retrieve an exact number of rows using the
%ROWCOUNT cursor attribute
* Determine when to exit the loop using the
%NOTFOUND cursor attribute
LOOP
FETCH item_cursor INTO v_product_id, v_item_total;
EXIT WHEN item_cursortROWCOUNT > 5
Trang 19Explicit Cursor Attributes continued
¬ Ô .Ắ Ắ.ẮốỐẮÚ a.aaAA AÁ.IÁA E OH OSES
You can only fetch rows when the cursor is open Determine whether the cursor is open using the %ISOPEN cursor attribute, if necessary
Fetch rows in a loop Determine when to exit the loop by using cursor attributes
To retrieve an exact number of rows, fetch the rows in a numeric FOR loop, or fetch the rows in a simple loop and determine when to exit the loop by using the
%ROWCOUNT cursor attribute
CURSOR item cursor IS
SELECT productid, price * quantity
FETCH item cursor INTO v_product_id, v_item total;
EXIT WHEN item_cursor%ROWCOUNT > 5
Note: If using Z7ROWCOUNT, add a test for no rows in the cursor by using the
%NOTFOUND attribute because the rowcount is not incremented if the fetch does not retrieve any rows
Processing Queries by Using Explicit Cursors 24-19
Trang 20ORACLE’
ieee ee ee ee ee eee ee eee eee ee eee eee eee ee eee eee eee eee eee eee ee eee
Cursors and Records: Example
Process the rows of the active set conveniently by
fetching values into a PL/SQL RECORD
CURSOR emp cursor IS
FROM 3 emp WHERE dept_id = 41;
emp record eømp Cursor$ROWTYPE;
BEGIN
OPEN emp cursor;
FETCH emp cursor INTO emp record;
24-20 Introduction to Oracle: SQL and PL/SQL Using Procedure Builder