【问题标题】:How do i continue running my program after encountering exception in SQL?在 SQL 中遇到异常后如何继续运行我的程序?
【发布时间】:2016-08-04 02:16:38
【问题描述】:

我编写了一个 PL/SQL 代码来仅打印大于 id=4 的记录。我在程序中使用了goto语句,在异常中没有检测到。遇到异常后请帮我继续程序。 我的代码是

declare
    cursor cur is select * from student;
    c student%rowtype;
    lt3 exception;
    PRAGMA
    exception_init(lt3,-77);
begin
    open cur;
    loop
        <<backup>>
        fetch cur into c;
        if c.id < 4 then
            raise lt3;
        else
            dbms_output.put_line(c.name);
        end if;
    end loop;
    close cur;
exception
    when lt3 then
    dbms_output.put_line('Exception encountered');
    goto backup;
end;
/

我应该在哪里改变?

我收到了错误

ERROR at line 24:
ORA-06550: line 24, column 7:
PLS-00201: identifier 'BACKUP' must be declared
ORA-06550: line 24, column 2:
PL/SQL: Statement ignored

【问题讨论】:

  • 真的需要使用异常吗?
  • @brenners1302 我的意思是使用异常,并希望在命中后继续执行。
  • 为什么不改变光标只选择 id 大于 4 的学生?
  • 大声笑,我问你是否真的需要异常,你回答你的意思是使用异常?然后你接受了一个不解决使用异常的答案。

标签: sql oracle exception plsql goto


【解决方案1】:

当您在cursor 中使用goto 时,光标将被关闭,因此您无法实现预期的行为。

来自Doc

如果使用 GOTO 语句提前退出游标 FOR 循环, 光标自动关闭。光标也关闭了 如果在循环内引发异常,则自动执行。

您可以做的一件事是在循环中使用continuebreakexit 来控制执行

open cur;
loop
    fetch cur into c;
    if c.id < 4 then
          continue;
    else
          dbms_output.put_line(c.name);
    end if;
end loop;
close cur;

【讨论】:

    【解决方案2】:

    如果可以,您应该避免在任何代码中使用 goto 语句。

    下面的代码应该可以实现您想要做的事情。我无权访问数据库,因此可能存在一些不正确的语法。

    declare
        cursor cur is select * from student;
        c student%rowtype;
        lt3 exception;
        PRAGMA
        exception_init(lt3,-77);
    begin
        open cur;
        loop
        begin
                fetch cur into c;
                if c.id < 4 then
            raise lt3;
                else
                    dbms_output.put_line(c.name);
                end if;
        exception
            when lt3 then
            dbms_output.put_line('Exception encountered');
        end;
        end loop;
        close cur;
    exception
        when others then
        dbms_output.put_line('other error encountered');
    end;
    

    【讨论】:

      【解决方案3】:

      您确实应该选择 id>4 以避免异常。

      Goto 不会以这种方式工作。您需要使用 continue 或 break 进行执行控制。

      【讨论】:

        猜你喜欢
        • 2020-11-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 2011-12-09
        相关资源
        最近更新 更多