How to fetch Oracle reference cursor into table variable? How to fetch Oracle reference cursor into table variable? oracle oracle

How to fetch Oracle reference cursor into table variable?


The name of variable in code above misleaded you. Your variable outtable is in table type. It isn't possible to fetch record data into table of records, but you can fetch it into record itself.

DECLARE     REFCUR SYS_REFCURSOR;       TYPE RECORDTYPE IS RECORD (COL1 NUMBER, COL2  VARCHAR(100));    outtable RECORDTYPE; BEGIN     SP_OUT_RefCur_PARAM(REFCUR);    LOOP        FETCH REFCUR INTO outtable;        EXIT WHEN REFCUR%NOTFOUND;        dbms_output.put_line(outtable.col1);    END LOOP;    CLOSE REFCUR;END;

Update: If you want to fetch all data for better performance your application you need to use BULK COLLECT statement:

DECLARE     REFCUR SYS_REFCURSOR;       TYPE RECORDTYPE IS        RECORD (COL1 NUMBER, COL2  VARCHAR(100));    TYPE TABLETYPE IS        TABLE OF REFTABLETYPE        INDEX BY PLS_INTEGER;    outtable TABLETYPE; BEGIN     SP_OUT_RefCur_PARAM(REFCUR);    LOOP        FETCH REFCUR INTO BULK COLLECT outtable;        EXIT WHEN outtable.COUNT = 0;        FOR indx IN 1 .. outtable.COUNT         LOOP            dbms_output.put_line(outtable(indx).col1);;        END LOOP;    END LOOP;    CLOSE REFCUR;END;

Note: memory consumption with the BULK statement is much more than without.

The most important thing to remember when you learn about and start to take advantage of features such as BULK COLLECT is that there is no free lunch. There is almost always a trade-off to be made somewhere. The tradeoff with BULK COLLECT, like so many other performance-enhancing features, is "run faster but consume more memory." (Oracle Magazine)

But if you are just fetching and processing the rows - a row at a time there is no needs in BULK statement, just use the cursor FOR LOOP. (Ask Tom)


Another way to do it is this one:

DECLARE     REFCUR SYS_REFCURSOR;       TYPE REFTABLETYPE IS RECORD (COL1 NUMBER, COL2  VARCHAR(100));    TYPE TABLETYPE IS TABLE OF REFTABLETYPE;    outtable TABLETYPE; BEGIN     SP_OUT_RefCur_PARAM(REFCUR);    FETCH REFCUR BULK COLLECT INTO outtable;     FOR i in outtable.First..outtable.Last Loop        dbms_output.put_line(outtable(i).col1);    END LOOP;    CLOSE REFCUR;END;