2013-02-27 43 views
1

我正在嘗試執行接收REFCURSOR並執行一些數據操作的函數。將RefCursor傳遞給函數時無效光標

爲了測試我的功能我有這樣的SQL/PLUS代碼:

var some_cursor REFCURSOR; 

exec :some_cursor := SCHEMA.test_getcursor; 

print some_cursor; 

variable res varchar2; 

exec :res := SCHEMA.second_function(:some_cursor, 'Other_parameter'); 

print res; 

現在,第一test_getcursor函數是一個簡單的函數,打開遊標,執行select查詢並返回光標。它工作得很好,它也打印some_cursor也很好。

當我調用second_function並將refcursor傳遞給它時,會發生此問題。

功能具有下面的代碼:

type cursor_row 
IS RECORD 
(field_1 some_field1%type, 
field_2 some_field2%type, 
field_3 some_field3%type); 

new_row cursor_row; 

BEGIN 
LOOP 
fetch PASSED_IN_REFCURSOR INTO new_row --this is where the function fails 
...data manipulation... 
EXIT WHEN PASSED_IN_REFCURSOR%NOTFOUND; 
END LOOP; 
CLOSE PASSED_IN_REFCURSOR; 
END; 

我得到的錯誤是Invalid Cursor

我確定我創建的類型具有與參考遊標相同數量的行和相同的數據類型。

我在這種情況下做錯了什麼?我使用Oracle 10g中,PL/SQL 10.2

回答

3

這是你的問題:

print some_cursor; 

將其刪除。通過打印光標,您已經獲取了所有記錄並關閉了它。所以第二個函數不能再讀取它了。

例如;

SQL> create procedure two(p_rc sys_refcursor) 
    2 is 
    3 v_col varchar2(1); 
    4 begin 
    5 loop 
    6  fetch p_rc into v_col; 
    7  exit when p_rc%notfound; 
    8  dbms_output.put_line(v_col); 
    9 end loop; 
10 end; 
11/

Procedure created. 

SQL> set serverout on 
SQL> var rc refcursor; 
SQL> exec :rc := one; 

PL/SQL procedure successfully completed. 

SQL> exec two(:rc); 
X 

PL/SQL procedure successfully completed. 

VS

SQL> var rc refcursor; 
SQL> exec :rc := one; 

PL/SQL procedure successfully completed. 

SQL> print rc 

D 
- 
X 

SQL> exec two(:rc); 
BEGIN two(:rc); END; 

* 
ERROR at line 1: 
ORA-01001: invalid cursor 
ORA-06512: at "TEST.TWO", line 6 
ORA-06512: at line 1 

其上彈了取當光標未打開。您應該首先檢查%isopen並提出一個定義的錯誤,如果您想提供更有用的錯誤。

+0

使用函數和存儲過程有什麼不同嗎?它看起來像當我使用一個函數並做同樣的事情時,它回來說'錯誤報告:光標已關閉' – Victor 2013-02-27 17:03:55