检查SYS_REFCURSOR是否为空的最佳方法

时间:2013-08-05 12:32:50

标签: sql oracle plsql 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;

这似乎没有用,有什么帮助吗?Ty

5 个答案:

答案 0 :(得分: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语句的INTO子句中,一个用于TABLE1和TABLE2中的每一列。另请注意,写入此游标的方式可能会比您预期的更多行返回;因为没有指定连接条件,所以你会得到所谓的笛卡尔连接,其中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 :(得分:0)

我们使用两个程序来执行结果

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;

上述过程将帮助您了解光标是否包含行

答案 2 :(得分: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;

答案 3 :(得分:0)

这项工作对我来说:D

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

答案 4 :(得分:0)

您还可以通过在打开游标之前执行select count()查询,然后按以下方式检查它来选择变量中的计数:

select count(*) into v_count from table1;
if v_count>0 then
    --do this
    open my_cursor for 
        select var1,var2,var3 from table1;
    fetch etc.
else
    --do that
end if;
相关问题