Escolar Documentos
Profissional Documentos
Cultura Documentos
7-1
Cursors
Every SQL statement executed by the Oracle server has an
associated individual cursor:
Implicit cursors: Declared and managed by PL/SQL for all
DML and PL/SQL SELECT statements
Explicit cursors: Declared and managed by the programmer
7-2
Table
100 King
Active set
7-3
AD_PRES
139 Seo
ST_CLERK
140 Patel
ST_CLERK
No
DECLARE
OPEN
FETCH
active set.
current
row into
variables.
EMPTY?
Test for
existing
rows.
Return to
FETCH if
rows are
found.
7-4
Yes
CLOSE
Release the
active set.
Fetch a row.
Cursor
pointer
7-5
Cursor
pointer
Examples:
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
DECLARE
v_locid NUMBER:= 1700;
CURSOR c_dept_cursor IS
SELECT * FROM departments
WHERE location_id = v_locid;
...
7-6
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
...
BEGIN
OPEN c_emp_cursor;
7-8
7-9
7 - 11
...
LOOP
FETCH c_emp_cursor INTO empno, lname;
EXIT WHEN c_emp_cursor%NOTFOUND;
DBMS_OUTPUT.PUT_LINE( v_empno ||' '||v_lname);
END LOOP;
CLOSE c_emp_cursor;
END;
/
7 - 12
7 - 14
DECLARE
CURSOR c_emp_cursor IS
SELECT employee_id, last_name FROM employees
WHERE department_id =30;
BEGIN
FOR emp_record IN c_emp_cursor
LOOP
DBMS_OUTPUT.PUT_LINE( emp_record.employee_id
||' ' ||emp_record.last_name);
END LOOP;
END;
/
7 - 15
Type
Description
%ISOPEN
Boolean
%NOTFOUND
Boolean
%FOUND
Boolean
%ROWCOUNT
Number
7 - 16
%ISOPEN Attribute
Fetch rows only when the cursor is open.
Use the %ISOPEN cursor attribute before performing a fetch
to test whether the cursor is open.
Example:
IF NOT c_emp_cursor%ISOPEN THEN
OPEN c_emp_cursor;
END IF;
LOOP
FETCH c_emp_cursor...
7 - 17
7 - 18
7 - 19
OPEN
7 - 20
cursor_name(parameter_value,.....) ;
DECLARE
CURSOR
c_emp_cursor (deptno NUMBER) IS
SELECT employee_id, last_name
FROM
employees
WHERE
department_id = deptno;
...
BEGIN
OPEN c_emp_cursor (10);
...
CLOSE c_emp_cursor;
OPEN c_emp_cursor (20);
...
7 - 21
7 - 22
7 - 24
7 - 25
Summary
In this lesson, you should have learned how to:
Distinguish cursor types:
Implicit cursors are used for all DML statements and singlerow queries.
Explicit cursors are used for queries of zero, one, or more
rows.
7 - 26
Practice 7: Overview
This practice covers the following topics:
Declaring and using explicit cursors to query rows of a table
Using a cursor FOR loop
Applying cursor attributes to test the cursor status
Declaring and using cursors with parameters
Using the FOR UPDATE and WHERE CURRENT OF clauses
7 - 27