Using Ref Cursors To Return Recordsets
The Reference Cursor which is also called the Cursor Variables is available since Oracle 7.3 the
The following procedure opens a query using a REF CURSOR
type has been available to allow recordsets to be returned from stored procedures and functions. Oracle 9i introduced the predefined SYS_REFCURSOR
type, meaning we no longer have to define our own REF CURSOR
types. The example below uses a ref cursor to return a subset of the records in the EMP
table.SYS_REFCURSOR
output parameter. Notice the cursor is not closed in the procedure. It is up to the calling code to manage the cursor once it has been opened.CREATE OR REPLACE PROCEDURE get_emp_rs (p_deptno IN emp.deptno%TYPE, p_recordset OUT SYS_REFCURSOR) AS BEGIN OPEN p_recordset FOR SELECT ename, empno, deptno FROM emp WHERE deptno = p_deptno ORDER BY ename; END GetEmpRS; /
The resulting cursor can be referenced from PL/SQL as follows.
SET SERVEROUTPUT ON SIZE 1000000 DECLARE l_cursor SYS_REFCURSOR; l_ename emp.ename%TYPE; l_empno emp.empno%TYPE; l_deptno emp.deptno%TYPE; BEGIN get_emp_rs (p_deptno => 30, p_recordset => l_cursor); LOOP FETCH l_cursor INTO l_ename, l_empno, l_deptno; EXIT WHEN l_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE(l_ename || ' | ' || l_empno || ' | ' || l_deptno); END LOOP; CLOSE l_cursor; END; /
No comments:
Post a Comment