Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I fetch the data from the SYS_REFCURSOR from one stored proc and use it in another?

I have a stored proc with the basic layout below that returns a sys_refcursor as a result set. (Technically it reurns four but for the sake of clarity I just say one). The result set is a selection from a temp table.

procedure aProcedure
( C1 in out sys_refcursor
) is
begin
--populate Temp_Table here with a stored proc call;
OPEN C1 FOR
SELECT Cols
FROM TEMP_TABLE;

I need to insert this result set from C1 into a permanent table using a different stored procedure. Is this Do-able or do I need to re-build the result set all over again?

I've been able to find information on working with cursors and result sets outside of oracle but not for working with them within itself.

I know it might make sense to just do the insert from the first stored proc but that's not really how I need it to happen. It's an optional requirement to save the result set permanently.

Thanks for any helpful info.

like image 270
dee Avatar asked Apr 05 '12 18:04

dee


1 Answers

Assuming that the caller knows the structure of the cursor that aProcedure is opening, you can do something like this.

declare
  l_rc sys_refcursor;
  l_rec temp_table%rowtype;
begin
  aProcedure( l_rc );
  loop
    fetch l_rc
     into l_rec;
    exit when l_rc%notfound;

    dbms_output.put_line( l_rec.col1 );
  end loop;
  close l_rc;
end;
/

If you can't fetch into a record type, you can also fetch into a number of other scalar local variables (the number and type have to match the number and type of columns that aProcedure specifies in its SELECT list). In my case, I defined aProcedure to return two numeric columns

declare
  l_rc sys_refcursor;
  l_col1 number;
  l_col2 number;
begin
  aProcedure( l_rc );
  loop
    fetch l_rc
     into l_col1, l_col2;
    exit when l_rc%notfound;
    dbms_output.put_line( l_col1 );
  end loop;
  close l_rc;
end;
like image 53
Justin Cave Avatar answered Oct 07 '22 11:10

Justin Cave