Search code examples
oracle-databasefunctionplsqlcursor

Function to return a cursor in PL SQL,


I have a function which returns a SYS_REFCURSOR, this function is to be called from different packages and we don't want to have to duplicate the cursor definition in multiple places.

FUNCTION f_get_cur(p_date DATE, p_code VARCHAR(10)) RETURN SYS_REFCURSOR IS
  cur_s SYS_REFCURSOR;
BEGIN
  OPEN cur_s FOR
    SELECT .blah blah etc etc

  return cur_s;
END f_get_cur;

Which compiles ok, however when I want to use the function in a FOR LOOP where I'd normally put the cursor I get the following error

Error: PLS-00456: item 'f_get_cur' is not a cursor

I'm attempting to open the cursor like so...

FOR cc_rec IN f_get_cur(c_date, p_c_code) LOOP

Am I using the wrong data type? Is there some other way of achieving what I'm trying?


Solution

  • I managed to get this working by creating another(!) cursor which implements the function I already created (which wraps the original cursor)

    cursor cur_real(cp_date DATE, cd_code VARCHAR2(10)) IS
      select ... etc
    FROM TABLE(f_get_cur(cp_date, cp_code));
    

    I can now use the cursor like so

    FOR cc_rec IN f_get_cur(c_date, p_c_code) LOOP
       do stuff ... etc
    END LOOP