6 Explicit Cursors
6 Explicit Cursors
Objectives
6-2
About Cursors
Every SQL statement executed by the Oracle Server has an individual cursor associated with it:
Implicit cursors: Declared for all DML and PL/SQL SELECT statements
6-3
Active set
Cursor
.
ST_CLERK ST_CLERK .
6-4
DECLARE
OPEN
FETCH
CLOSE
Create a
named SQL area
Identify
the active set
Load the
current row into variables
Test for
existing rows
Release
the active set
Return to
FETCH if rows are found
6-5
6-6
Cursor pointer
Continue until empty.
6-7
6-8
Syntax:
CURSOR cursor_name IS select_statement;
Do not include the INTO clause in the cursor declaration. If processing rows in a specific sequence is required, use the ORDER BY clause in the query.
6-9
Example:
DECLARE CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; CURSOR dept_cursor IS SELECT * FROM departments WHERE location_id = 170; BEGIN ...
6-10
Syntax:
OPEN cursor_name;
Open the cursor to execute the query and identify the active set. If the query returns no rows, no exception is raised. Use cursor attributes to test the outcome after a fetch.
6-11
Syntax:
FETCH cursor_name INTO [variable1, variable2, ...] | record_name];
6-12
Example:
LOOP FETCH emp_cursor INTO v_empno,v_ename; EXIT WHEN ...; ... -- Process the retrieved data END LOOP;
6-13
Syntax:
CLOSE cursor_name;
Close the cursor after completing the processing of the rows. Reopen the cursor, if required. Do not attempt to fetch data from a cursor after it has been closed.
6-14
%ROWCOUNT
Number
6-15
Example:
IF NOT emp_cursor%ISOPEN THEN OPEN emp_cursor; END IF; LOOP FETCH emp_cursor...
6-16
Process several rows from an explicit cursor using a loop. Fetch a row with each iteration. Use explicit cursor attributes to test the success of each fetch.
6-17
6-18
Example
DECLARE v_empno employees.employee_id%TYPE; v_ename employees.last_name%TYPE; CURSOR emp_cursor IS SELECT employee_id, last_name FROM employees; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO v_empno, v_ename; EXIT WHEN emp_cursor%ROWCOUNT > 10 OR emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (TO_CHAR(v_empno) ||' '|| v_ename); END LOOP; CLOSE emp_cursor; END ;
6-20
employee_id 100
last_name King
6-21
Syntax:
FOR record_name IN cursor_name LOOP statement1; statement2; . . . END LOOP;
6-22
The cursor FOR loop is a shortcut to process explicit cursors. Implicit open, fetch, exit, and close occur. The record is implicitly declared.
Copyright Oracle Corporation, 2001. All rights reserved.
6-23
6-24
Summary
Manipulate explicit cursors Evaluate the cursor status by using cursor attributes Use cursor FOR loops
6-26
Practice 6 Overview
Declaring and using explicit cursors to query rows of a table Using a cursor FOR loop Applying cursor attributes to test the cursor status
6-27