Sub topic 3
Explicit cursors: declare, open, fetch, close
This chapter assumes you know basic SQL, the structure of an anonymous PL/SQL block, PL/SQL variables and control flow, and basic exception handling. It covers the full life cycle of an explicit cursor and the errors that appear when you skip a step.
Why explicit cursors exist
Oracle runs every SQL statement through a cursor. A cursor is a handle to a private work area, called the context area, where Oracle keeps the parsed statement, the active result set and the current position in it.
PL/SQL creates an implicit cursor for each DML statement and for each SELECT ... INTO. You do not control it. An explicit cursor is one you name, declare and drive yourself. You need one when a query can return more than one row and you want to process the rows one at a time. SELECT ... INTO raises TOO_MANY_ROWS for such a query.
An explicit cursor gives you control over when the query opens, how many rows you fetch at a time and when the resources are released.
The four steps
Every explicit cursor goes through the same four steps.
- Declare. You name the cursor and attach a
SELECTstatement in the declaration section. Nothing runs yet. - Open.
OPENallocates the context area, binds variables and runs the query. Oracle identifies the active set but does not copy all the rows to you. - Fetch.
FETCHmoves to the next row and copies its column values into variables or a record. You repeat this until no rows remain. - Close.
CLOSEreleases the context area and the resources it holds.
A complete example
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 50
ORDER BY last_name;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(r_emp.last_name || ': ' || r_emp.salary);
END LOOP;
CLOSE c_emp;
END;
/Walk through it in order.
CURSOR c_emp IS SELECT ...declares the cursor. The query is fixed at this point, andORDER BYmakes the fetch order predictable.r_emp c_emp%ROWTYPEdeclares a record with one field for each column in the select list. The field names come from the column names or aliases.OPEN c_empruns the query.FETCH c_emp INTO r_empcopies the next row into the record.EXIT WHEN c_emp%NOTFOUNDleaves the loop once a fetch finds no row.CLOSE c_empfrees the work area.
Declaring a cursor
A cursor declaration goes in the declaration section of a block, a subprogram or a package. The general form is:
CURSOR cursor_name [(parameter_list)] [RETURN return_type] IS select_statement;Three points matter in practice.
- The declaration does not run the query. It only records the text, so a syntax or privilege error in the
SELECTshows up when the block compiles, but data problems appear only atOPENorFETCH. - The query can refer to PL/SQL variables that are in scope. Oracle reads their values when you open the cursor, not when you declare it.
- The select list needs an alias for every expression.
%ROWTYPEbuilds a field from each select-list item, so an unaliased expression such assalary * 12gives you a field you cannot name in code.
DECLARE
l_dept NUMBER := 50;
CURSOR c_annual IS
SELECT last_name, salary * 12 AS annual_salary
FROM employees
WHERE department_id = l_dept;
r_annual c_annual%ROWTYPE;
BEGIN
l_dept := 80; -- changes the result set, because OPEN has not run yet
OPEN c_annual;
FETCH c_annual INTO r_annual;
DBMS_OUTPUT.PUT_LINE(r_annual.last_name || ': ' || r_annual.annual_salary);
CLOSE c_annual;
END;
/This block reads from department 80, not 50. The bind value is taken at OPEN.
Changing l_dept after the cursor is open does not affect the rows you fetch. The result set is fixed at the moment you open it.
Opening a cursor
OPEN does the following:
- Allocates memory for the context area.
- Binds the current values of any variables and parameters used in the query.
- Runs the query and fixes the result set as of that moment.
- Positions the cursor before the first row.
Oracle uses statement-level read consistency. The rows you fetch reflect the data as it was when you opened the cursor, even if other sessions commit changes while you are still fetching.
Opening a cursor that is already open raises ORA-06511: PL/SQL: cursor already open (CURSOR_ALREADY_OPEN). If you need to reuse a cursor, close it first, or check %ISOPEN.
Fetching rows
FETCH advances the cursor one row and copies the values into the target. You can fetch into:
- a record declared with
%ROWTYPE, which is the simplest option and adjusts itself when the query changes; - a list of scalar variables, one for each column and in the same order.
DECLARE
CURSOR c_emp IS
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = 50;
l_id employees.employee_id%TYPE;
l_name employees.last_name%TYPE;
l_sal employees.salary%TYPE;
BEGIN
OPEN c_emp;
FETCH c_emp INTO l_id, l_name, l_sal;
WHILE c_emp%FOUND LOOP
DBMS_OUTPUT.PUT_LINE(l_id || ' ' || l_name || ' ' || l_sal);
FETCH c_emp INTO l_id, l_name, l_sal;
END LOOP;
CLOSE c_emp;
END;
/Here the first FETCH sits before the loop. The loop condition %FOUND is then tested after each fetch, and the second FETCH at the end of the body gets the next row. This is the usual WHILE pattern. If you forget the second FETCH, the loop never ends.
The target must match the select list in number and in compatible types. If it does not, you get a compile-time error such as PLS-00394: wrong number of values in the INTO list of a FETCH statement.
When a fetch finds no row, the target variables keep the values from the previous successful fetch. Do not read them after %NOTFOUND becomes true.
Closing a cursor
CLOSE releases the context area. After it runs, the result set is gone and you cannot fetch from the cursor. Fetching from or closing a cursor that is not open raises ORA-01001: invalid cursor (INVALID_CURSOR).
Closing matters for three reasons.
- Each open cursor counts against the
OPEN_CURSORSinitialization parameter for the session. Leaked cursors eventually raiseORA-01000: maximum open cursors exceeded. - An open cursor holds memory in the session.
- Closing is deterministic, whereas waiting for the block to end is not something to rely on when the cursor is declared in a package, because a package-level cursor stays open for the whole session unless you close it.
Cursors declared inside a block are closed automatically when the block ends, but you should not depend on that. An exception can also leave a cursor open if the handler is in an outer block that has a longer life.
Errors and the safe pattern
An exception between OPEN and CLOSE skips the CLOSE. A cleanup step in the exception handler fixes that.
DECLARE
CURSOR c_emp IS
SELECT employee_id, salary
FROM employees
WHERE department_id = 50;
r_emp c_emp%ROWTYPE;
BEGIN
OPEN c_emp;
LOOP
FETCH c_emp INTO r_emp;
EXIT WHEN c_emp%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(r_emp.employee_id || ': ' || r_emp.salary);
END LOOP;
CLOSE c_emp;
EXCEPTION
WHEN OTHERS THEN
IF c_emp%ISOPEN THEN
CLOSE c_emp;
END IF;
RAISE;
END;
/The handler tests %ISOPEN first, because closing a cursor that is not open would raise a second error that hides the first. RAISE with no argument passes the original error to the caller, so the cleanup does not swallow it.
Common errors
| Error | Cause | Fix |
|---|---|---|
| `ORA-06511` cursor already open | `OPEN` on an open cursor, often inside a loop | `CLOSE` before reopening, or test `%ISOPEN` |
| `ORA-01001` invalid cursor | `FETCH` or `CLOSE` on a cursor that is not open | `OPEN` first, and do not fetch after `CLOSE` |
| `ORA-01000` maximum open cursors exceeded | Cursors opened and never closed | Close every cursor, including in exception paths |
| `PLS-00394` wrong number of values | Fetch target does not match the select list | Use a `%ROWTYPE` record |
| Last row printed twice | Loop body uses the record before the exit test | Put `EXIT WHEN ... %NOTFOUND` right after `FETCH` |
Reopening a cursor
You can open the same cursor several times in a block, provided it is closed between uses. Each OPEN re-evaluates the variables in the query, so the result set can change.
DECLARE
CURSOR c_emp IS
SELECT last_name
FROM employees
WHERE department_id = l_dept;
BEGIN
NULL;
END;
/This block does not compile, and the reason is a good one to remember. The query uses l_dept, which is not declared before the cursor. A variable must be declared above the cursor that refers to it. Move l_dept NUMBER; above the CURSOR line, or use a cursor parameter, which a later chapter covers.
Summary of the rules
- Declare the cursor and its record in the
DECLAREsection. OPENonce, fetch in a loop, test%NOTFOUNDstraight after eachFETCH, thenCLOSE.- Add an exception handler that closes the cursor if
%ISOPENis true. - Prefer
%ROWTYPErecords to lists of scalar variables. - When you do not need this much control, the cursor
FORloop in a later chapter does the open, fetch and close for you.
Exercise
A block opens cursor c_emp, then a PL/SQL statement inside the fetch loop raises an unhandled exception. The CLOSE statement comes after the loop. What happens to the cursor, and how do you make the block safe?
Show answer
The exception skips the CLOSE, so the cursor stays open until the block exits or the session ends, and repeated runs can reach ORA-01000. Add an EXCEPTION section that tests c_emp%ISOPEN, closes the cursor if it is open, and then re-raises the error with RAISE.
Exercise
What does this block do on its second FETCH when department 50 has only one employee, and why can it print the same name twice? DECLARE CURSOR c IS SELECT lastname FROM employees WHERE departmentid = 50; lname employees.lastname%TYPE; BEGIN OPEN c; LOOP FETCH c INTO lname; DBMSOUTPUT.PUTLINE(lname); EXIT WHEN c%NOTFOUND; END LOOP; CLOSE c; END;
Show answer
The second FETCH finds no row, so c%NOTFOUND becomes true, but lname keeps the value from the first fetch. The PUTLINE runs before the EXIT test, so the same name prints a second time. Move EXIT WHEN c%NOTFOUND directly after the FETCH.