Search code examples
plsqlref-cursorsys-refcursor

PL/SQL Static cursor variable as ref cursor


I have a procedure that takes a SYS_REFCURSOR and converts it to JSON.

In a procedure that calls the above, I'm trying define a CURSOR as normal and supply that as a REF CURSOR.

I'm receiving PLS-00361.

I understand that I can use the OPEN FOR construct, but I need to use my Cursor elsewhere and don't like the duplication.

Any advice?

  PROCEDURE LIST_EMPLOYEES 
  AS

    l_ref_cursor SYS_REFCURSOR;

    CURSOR c_emps
    IS
    SELECT email_address
      FROM employees;

  BEGIN

    OPEN c_emps;
    FETCH c_emps INTO l_ref_cursor;

    json_utils.refcursor_to_json_via_http(l_ref_cursor,
                                          'employees');

    CLOSE l_ref_cursor;

  EXCEPTION
  WHEN others
  THEN
    log_error;
  END LIST_EMPLOYEES;

Regards, Laurence.


Solution

  • You wouldn't fetch the cursor into the REF CURSOR, you would simply OPEN it:

    PROCEDURE LIST_EMPLOYEES AS
    
       l_ref_cursor SYS_REFCURSOR;
    
    BEGIN
    
       OPEN l_ref_cursor FOR SELECT email_address FROM employees;
    
       json_utils.refcursor_to_json_via_http(l_ref_cursor, 'employees');
    
       CLOSE l_ref_cursor;
    
    END LIST_EMPLOYEES;