Fetch and bulk collect from a REF CURSOR returned by a procedure

旧巷老猫 提交于 2019-12-08 06:08:59

问题


I have a stored procedure that has a SYS_REFCURSOR as an OUT parameter. The signature is, for example, as follows:

PROCEDURE myProc(p_someID IN INTEGER, p_cursor OUT SYS_REFCURSOR);

I call this procedure from a function, where I have to copy a column named clientID from the p_cursor to a scalar nested table.

I am doing as follows:

CREATE OR REPLACE FUNCTION myFunction
    RETURN sys_refcursor
IS
    someID      INTEGER       := 1234;
    myCursor    SYS_REFCURSOR;
    TYPE t_clientID_nt IS TABLE OF NUMBER(16,0);
    clientID_nt t_clientID_nt;
    otherID     SYS_REFCURSOR;
BEGIN
    myProc (someID, myCursor);
    FOR i IN myCursor
    LOOP
        clientID_nt.EXTEND;
        clientID_nt (clientID_nt.COUNT) := i.clientID;
    END LOOP;


    -- Other code that opens the cursor otherID
    -- based on the IDs in clientID_nt
    ...
    ... 
    RETURN otherID;
END;
/

When I try to compile this function, the error I get is:

PLS-00221: 'CLIENTID_NT' is not a procedure or is undefined

and it is at line 11 of the code.

Any help on how to fetch and bulk collect from such a cursor is greatly appreciated.


回答1:


It's not allowed to use cursor variables in the for cursor loop (FOR i IN myCursor). You have to fetch from the cursor variable explicitly one row at a time, using FETCH INTO statement and regular loop statement for instance or use FETCH BULK COLLECT INTO to populate a collection. For instance:

SQL> declare
  2    TYPE t_clientID_nt IS TABLE OF dual%rowtype;
  3    clientID_nt t_clientID_nt;
  4  
  5    l_cur sys_refcursor;
  6  
  7    procedure OpenAndPopulateCursor(p_cur in out sys_refcursor) is
  8    begin
  9      open p_cur for
 10        select *
 11         from dual;
 12    end;
 13  
 14  begin
 15    OpenAndPopulateCursor(l_cur);
 16  
 17    if l_cur%isopen
 18    then
 19      fetch l_cur bulk collect into clientID_nt;
 20    end if;
 21  
 22    dbms_output.put_line(concat( to_char(clientID_nt.count) 
 23                               , ' record(s) has/have been fetched.'));
 24  end;
 25  /

 1 record(s) has/have been fetched.

 PL/SQL procedure successfully completed


来源:https://stackoverflow.com/questions/19562603/fetch-and-bulk-collect-from-a-ref-cursor-returned-by-a-procedure

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!