从过程返回的REF CURSOR获取和批量收集

时间:2013-10-24 09:52:35

标签: oracle plsql oracle11g cursor oracle11gr2

我有一个SYS_REFCURSOR作为OUT参数的存储过程。签名例如如下:

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

我从一个函数调用此过程,我必须将clientID中名为p_cursor的列复制到标量嵌套表。

我的做法如下:

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;
/

当我尝试编译此函数时,我得到的错误是:

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

,它位于代码的第11行。

非常感谢任何有关如何从这样的光标获取和批量收集的帮助。

1 个答案:

答案 0 :(得分:6)

不允许在for游标循环(FOR i IN myCursor)中使用游标变量。您必须一次显式地从游标变量中获取一行,例如使用FETCH INTO语句和常规循环语句,或使用FETCH BULK COLLECT INTO填充集合。例如:

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