如何编写条件以执行for循环不返回任何行的操作

问题描述

在此循环中,我想捕获没有在循环中返回数据的函数,以执行else命令或没有数据时的异常。但这是行不通的。请帮我正确的语法或解决方法谢谢!

begin
    --looping 
    for i in (
    select x,y,z,rownum
        from period
    where x = 0   -- here this query does not return a row
                
    ) loop 

    begin
      if sql%rowcount >=1  -- tried row count 
        then 
        dbms_output.put_line ('blablabla');
        
        else
        dbms_output.put_line ('blueeeeeee');
        end if;
        
        exception when no_data_found  --tried this exception
        then 
        dbms_output.put_line ('black');
        end;
        end loop;
end;

解决方法

如果您在for循环中的查询不返回行,则您将永远不会进入此循环的正文,因此 您应该使用open-cursor-fetch-close或手动检查,例如:

declare
   loop_flag boolean:=false;
   loop_n   int:=0;
begin
    --looping 
    for i in (
    select x,y,z,rownum
        from period
    where x = 0   -- here this query does not return a row
    ) 
    loop 
        -- processing fetched row:
        loop_n:=loop_n+1;
        loop_flag:=true;
        if loop_n = 1  
        then
            dbms_output.put_line ('first row: ' || r.x );
        else
            dbms_output.put_line ('other rows...');
        end if;
    end loop;
    if not loop_flag then 
        dbms_output.put_line ('no data found...');
    end;
end;