Sub topic 11
REF CURSOR and SYS_REFCURSOR
This chapter assumes you can write an anonymous PL/SQL block and handle exceptions. It also assumes you know the explicit cursor lifecycle (declare, open, fetch, close) and the cursor attributes %FOUND, %NOTFOUND and %ISOPEN.
Static cursors and cursor variables
An explicit cursor is tied to one query when you declare it. You can pass arguments to it, but the query text stays the same. A cursor variable is different. It is a variable that points to a cursor, and you choose the query when you run OPEN ... FOR. The type of a cursor variable is a REF CURSOR.
Cursor variables help in three situations:
- The query is only known at run time, for example because the user picks a sort order.
- One program unit builds a result set and another consumes it.
- A client application, such as Java, Python or SQL*Plus, needs to receive a result set from a stored subprogram.
Strong and weak REF CURSOR types
You declare a REF CURSOR type with TYPE ... IS REF CURSOR. Whether you add a RETURN clause decides how strictly Oracle checks the queries you attach to it.
| Kind | Declaration | Compile-time check | Typical use |
|---|---|---|---|
| Strong | `TYPE t IS REF CURSOR RETURN employees%ROWTYPE;` | The query must match the return type | Packages where the shape of the result is part of the contract |
| Weak | `TYPE t IS REF CURSOR;` | None; any query is accepted | Flexible procedures and dynamic queries |
| Predefined weak | `SYS_REFCURSOR` | None | Most new code; no type declaration needed |
SYS_REFCURSOR is a weak REF CURSOR type that Oracle predefines, so you can declare variables and parameters of that type directly. Because it is shared, a function from one package can return it to a caller in another package without either side declaring a type.
Strong types give you a compile-time error if the query does not match. Weak types defer the check to the FETCH. A mismatch then raises ROWTYPE_MISMATCH (ORA-06504) at run time, or a conversion error.
Opening and fetching from a cursor variable
The basic pattern uses OPEN ... FOR, a fetch loop and CLOSE.
DECLARE
l_rc SYS_REFCURSOR;
l_name employees.last_name%TYPE;
l_sal employees.salary%TYPE;
BEGIN
OPEN l_rc FOR
SELECT last_name, salary
FROM employees
WHERE department_id = 50;
LOOP
FETCH l_rc INTO l_name, l_sal;
EXIT WHEN l_rc%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(l_name || ': ' || l_sal);
END LOOP;
CLOSE l_rc;
END;
/The attributes work the same way as for named cursors, and you apply them to the variable. Two differences matter:
- You cannot use a cursor FOR loop with a REF CURSOR variable. The cursor FOR loop needs a query or a named static cursor that it can open itself. With a cursor variable you write
FETCH,EXIT WHENandCLOSEyourself. - You can reopen a cursor variable that is already open. Oracle closes the previous query for you. Reopening a static explicit cursor that is already open raises
CURSOR_ALREADY_OPEN(ORA-06511).
A strongly typed cursor variable
With a strong type, the query is checked when the block compiles. This lets you fetch into a %ROWTYPE record.
DECLARE
TYPE t_emp_rc IS REF CURSOR RETURN employees%ROWTYPE;
l_rc t_emp_rc;
l_emp employees%ROWTYPE;
BEGIN
OPEN l_rc FOR
SELECT *
FROM employees
WHERE department_id = 50;
LOOP
FETCH l_rc INTO l_emp;
EXIT WHEN l_rc%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(l_emp.last_name || ' earns ' || l_emp.salary);
END LOOP;
CLOSE l_rc;
END;
/If you replaced SELECT * with SELECT last_name, the block would fail to compile, because the select list does not match employees%ROWTYPE. A weak cursor variable would accept that query and fail only at the fetch.
Returning a result set from a function
The most common use of SYS_REFCURSOR is a function that builds a result set and hands it to a caller.
CREATE OR REPLACE FUNCTION get_dept_employees (p_dept IN NUMBER)
RETURN SYS_REFCURSOR
IS
l_rc SYS_REFCURSOR;
BEGIN
OPEN l_rc FOR
SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = p_dept
ORDER BY last_name;
RETURN l_rc;
END get_dept_employees;
/The function opens the cursor and does not close it. Closing it before RETURN would leave the caller with an unusable handle. The caller now owns the cursor and must close it.
DECLARE
l_rc SYS_REFCURSOR;
l_id employees.employee_id%TYPE;
l_name employees.last_name%TYPE;
l_sal employees.salary%TYPE;
BEGIN
l_rc := get_dept_employees(50);
LOOP
FETCH l_rc INTO l_id, l_name, l_sal;
EXIT WHEN l_rc%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(l_id || ' ' || l_name || ': ' || l_sal);
END LOOP;
CLOSE l_rc;
END;
/In SQL*Plus or SQL Developer you can also bind the result to a host variable and print it. The client then fetches the rows and closes the cursor for you.
VARIABLE rc REFCURSOR
EXEC :rc := get_dept_employees(50)
PRINT rcPassing a cursor variable to a procedure
A procedure can accept a SYS_REFCURSOR parameter and process the rows without knowing how the cursor was built. Use OUT or IN OUT mode if the procedure opens the cursor. Use IN if it only fetches and closes.
CREATE OR REPLACE PROCEDURE print_employees (p_rc IN SYS_REFCURSOR)
IS
l_id employees.employee_id%TYPE;
l_name employees.last_name%TYPE;
l_sal employees.salary%TYPE;
BEGIN
LOOP
FETCH p_rc INTO l_id, l_name, l_sal;
EXIT WHEN p_rc%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(l_id || ' ' || l_name || ': ' || l_sal);
END LOOP;
CLOSE p_rc;
END print_employees;
/
BEGIN
print_employees(get_dept_employees(50));
END;
/The fetch target in print_employees must match the select list of whatever query the caller opened. Three columns of compatible types work here. Any other shape fails at run time, because the parameter is weakly typed.
Dynamic queries with OPEN ... FOR
OPEN ... FOR also accepts a string, so the query text can be built at run time. Pass values as bind variables with USING, never by concatenating them into the string.
DECLARE
l_rc SYS_REFCURSOR;
l_name employees.last_name%TYPE;
l_sal employees.salary%TYPE;
BEGIN
OPEN l_rc FOR
'SELECT last_name, salary
FROM employees
WHERE department_id = :dept
AND salary >= :min_sal
ORDER BY salary DESC'
USING 50, 3000;
LOOP
FETCH l_rc INTO l_name, l_sal;
EXIT WHEN l_rc%NOTFOUND;
DBMS_OUTPUT.PUT_LINE(l_name || ': ' || l_sal);
END LOOP;
CLOSE l_rc;
END;
/Bind variables can stand in for values only. They cannot stand in for column names, table names or sort direction. When you need a different ORDER BY, choose the text from a fixed list in your own code and append it to the string. Do not append text received from a user.
CREATE OR REPLACE FUNCTION get_employees_sorted (
p_dept IN NUMBER,
p_sort IN VARCHAR2 DEFAULT 'NAME'
) RETURN SYS_REFCURSOR
IS
l_rc SYS_REFCURSOR;
l_order VARCHAR2(30);
BEGIN
l_order := CASE UPPER(p_sort)
WHEN 'NAME' THEN 'last_name'
WHEN 'SALARY' THEN 'salary DESC'
ELSE 'employee_id'
END;
OPEN l_rc FOR
'SELECT employee_id, last_name, salary
FROM employees
WHERE department_id = :dept
ORDER BY ' || l_order
USING p_dept;
RETURN l_rc;
END get_employees_sorted;
/Common errors and cleanup
| Symptom | Cause | Fix |
|---|---|---|
| ORA-01001 invalid cursor | Fetching from or closing a cursor variable that was never opened or is already closed | Check `%ISOPEN` before closing, and keep track of which unit owns the close |
| ORA-06504 return types of result set variables do not match | The fetch target or the query does not match the cursor variable's type | Align the select list with the record or variables, or use a strong type to catch it at compile time |
| ORA-06511 cursor already open | Reopening a static explicit cursor | Close it first. Cursor variables can be reopened without error |
| Open cursors keep growing (ORA-01000 maximum open cursors exceeded) | Callers never close cursors returned by functions | Close every cursor variable in the unit that finishes with it, including on the exception path |
A safe pattern closes the cursor in an exception handler as well as on the normal path.
DECLARE
l_rc SYS_REFCURSOR;
l_name employees.last_name%TYPE;
BEGIN
l_rc := get_dept_employees(50);
LOOP
FETCH l_rc INTO l_name;
EXIT WHEN l_rc%NOTFOUND;
END LOOP;
CLOSE l_rc;
EXCEPTION
WHEN OTHERS THEN
IF l_rc%ISOPEN THEN
CLOSE l_rc;
END IF;
RAISE;
END;
/In this block the fetch targets one column, but the function returns three. The fetch fails with ORA-06504 or a similar error, and the handler closes the cursor before re-raising it.
Choosing between the options
- Use a regular explicit cursor or a cursor FOR loop when the query is fixed and the rows are processed inside one program unit. This is simpler and the compiler checks everything.
- Use a strong REF CURSOR type when the shape of the result is part of an interface and you want compile-time checks.
- Use
SYS_REFCURSORwhen you return a result set to a client or to another unit, or when the query text varies at run time.
Exercise
Why can you not process a SYS_REFCURSOR variable with a cursor FOR loop, and what do you write instead?
Show answer
A cursor FOR loop opens, fetches from and closes a query or named static cursor that it controls. A cursor variable is opened elsewhere with OPEN ... FOR, so the loop has nothing to open. Write OPEN lrc FOR query, then a LOOP with FETCH lrc INTO ..., EXIT WHEN lrc%NOTFOUND, and finally CLOSE lrc.
Exercise
The function getdeptemployees opens a SYSREFCURSOR and returns it. A developer adds CLOSE lrc just before RETURN l_rc. What happens in the caller, and why?
Show answer
The caller receives a handle to a closed cursor. Its first FETCH raises ORA-01001 (invalid cursor). The function must leave the cursor open, and the caller closes it after fetching.