【问题标题】:How to write a condition to do something where a for loop returns no rows如何编写条件以执行 for 循环不返回任何行的操作
【发布时间】:2020-12-26 08:20:10
【问题描述】:

在这个循环中,我想捕获在循环中不返回数据的函数,以在没有数据时执行 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;

【问题讨论】:

    标签: sql oracle plsql oracle11g oracle19c


    【解决方案1】:

    如果你在 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;
    

    【讨论】:

    • ahhh lemme try that...我正在做这样的事情...cool coo lthanks lemme test
    • @JayKhan 我建议您也检查文档中的第一个选项open-fetch-closedocs.oracle.com/en/database/oracle/oracle-database/19/lnpls/…
    • 谢谢——我将编辑上面的代码,仅供阅读和测试的人使用..
    • @JayKhan 抱歉,忘记了not loop_flag - 现已修复
    猜你喜欢
    • 1970-01-01
    • 2022-09-28
    • 2021-11-11
    • 2011-12-18
    • 2014-09-20
    • 2017-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多