在 SQL 中遇到异常后如何继续 运行 我的程序?

How do i continue running my program after encountering exception in SQL?

我写了一个 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

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

来自Doc

If you use the GOTO statement to exit a cursor FOR loop prematurely, the cursor is closed automatically. The cursor is also closed automatically if an exception is raised inside the loop.

你可以做的一件事是在循环中使用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;

您应该尽可能避免在任何代码中使用 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;

你真的应该 select id>4 以避免异常。

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