2013-08-05 59 views
2

我有一個遊標,其中的值來自select,我想在執行某些操作之後執行某些操作,具體取決於我是否找到任何行或找不到任何行。檢查SYS_REFCURSOR是否爲空的最佳方法

recs_Table SYS_REFCURSOR; 

begin 

    open recs_Table for 
     select * from table1, table2; 


    if recs_Table%found then 
     --do this 
    else 
     --do that 
    end if; 

end; 

這似乎沒有工作,任何幫助嗎?泰

+3

您需要檢查您的查詢,打開,提取,關閉遊標。請參閱oracle docs:http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00605 – Art

回答

4

您需要使用FOUND屬性%之前執行FETCH反光標。你的代碼更改爲類似

DECLARE 
    recs_Table SYS_REFCURSOR; 
    nTable_1_value NUMBER; 
    nTable_2_value NUMBER; 
begin 

    open recs_Table for 
     select * from table1, table2; 


    FETCH recs_Table INTO nTable_1_value, nTable_2_value; 

    if recs_Table%found then 
     --do this 
    else 
     --do that 
    end if; 

end; 

請注意,你可能需要一個外部變量到FETCH語句,一個在Table 1和Table每一列的INTO子句的方式。還要注意,這個遊標寫入的方式可能會得到比您預期的更多的行;因爲沒有指定連接條件,您將得到所謂的笛卡爾連接,其中TABLE1中的每一行都連接到TABLE2中的每一行 - 因此,您將返回的行數是(TABLE1中的行數)* (TABLE2中的行數)。

一個潛在的更簡單的方式來做到這將是使用遊標FOR循環,如下:

DECLARE 
    bData_found BOOLEAN := FALSE; 
begin 
    FOR aRow IN (select * from table1, table2) 
    LOOP 
    -- If the program gets here, it means a row was fetched 

    -- do this 

    bData_found := TRUE; 

    EXIT; -- if you only care if data was found and don't want to 
      -- process all the rows 
    END LOOP; 

    IF NOT bData_found THEN 
    -- do that 
    END IF; 
end; 

分享和享受。

1

我們用兩個程序來執行結果

create or replace procedure pro_sample(recs_Table out SYS_REFCURSOR) is 

    begin 
     open recs_Table for 
      select * from table1, table2; 
    end; 

這上面的程序將被用於打開遊標

create or replace procedure pro_sample(recs_Table out SYS_REFCURSOR) is 
    sam sys_refcursor; 
    var number; 
       -- if you have any variables then declare them 
    begin 
    pro_sample(sam); 
    fetch sam into var; 
    if sam%found then 
     --do this 
     else 
     --do that 
    end if; 
    close sam; 
end; 

上述程序將幫助你瞭解遊標是否包含行或不是

0
create or replace procedure pro_sample(recs_Table out SYS_REFCURSOR) is 
    begin 
     open recs_Table for 
      select a,b,c,d from table1, table2; 
    end; 

create or replace function haveRows_pro_sample is 
sam sys_refcursor; 
var varchar(200); 
varOut number:=0; 
    begin 
     pro_sample(sam); 
     fetch sam into var,var,var,var; 
     if sam%found then 
      varOut :=1; 
     end if; 
     return varOut; 
    end; 
0

這工作對我來說:D

IF(MYCURSOR%ROWCOUNT = 0)THEN 
     DO SOMETHING ... 
    ENDIF; 
+0

只需解釋一下你的代碼 –

相關問題