Sobes.tech
Middle

How to return a value from a procedure using a REF CURSOR?

sobes.tech AI

Answer from AI

In Oracle PL/SQL, a REF CURSOR is often used to return a set of rows from a procedure. It is a pointer to the result of a query, which can be opened inside the procedure and returned to the calling code.

Example of a procedure with an OUT parameter of type REF CURSOR:

CREATE OR REPLACE PROCEDURE get_employees(p_dept_id IN NUMBER, p_refcur OUT SYS_REFCURSOR) AS
BEGIN
  OPEN p_refcur FOR
    SELECT employee_id, first_name, last_name
    FROM employees
    WHERE department_id = p_dept_id;
END;
/

Call from a PL/SQL block:

DECLARE
  rc SYS_REFCURSOR;
  emp_id employees.employee_id%TYPE;
  fname employees.first_name%TYPE;
  lname employees.last_name%TYPE;
BEGIN
  get_employees(10, rc);
  LOOP
    FETCH rc INTO emp_id, fname, lname;
    EXIT WHEN rc%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(emp_id || ' ' || fname || ' ' || lname);
  END LOOP;
  CLOSE rc;
END;
/

Thus, the procedure opens a REF CURSOR with the required query, and the calling code reads data from it.