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

在SQL中遇到异常后,如何继续运行程序?,sql,oracle,exception,plsql,goto,Sql,Oracle,Exception,Plsql,Goto,我编写了一个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 <&

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

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

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

您可以在循环中使用,
break
exit
来控制执行

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;
opencur;
环
把cur取到c中;
如果c.id<4,则
继续;
其他的
dbms_output.put_行(c.name);
如果结束;
端环;
封闭电流;

如果可以,您应该避免在任何代码中使用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;
声明
光标cur为从学生中选择*;
c学生%行类型;
lt3例外;
布拉格马
异常初始化(lt3,-77);
开始
开放cur;
环
开始
把cur取到c中;
如果c.id<4,则
提高lt3;
其他的
dbms_output.put_行(c.name);
如果结束;
例外
那么什么时候lt3呢
dbms_output.put_行(“遇到异常”);
结束;
端环;
封闭电流;
例外
当其他人
dbms_output.put_行(“遇到其他错误”);
结束;

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


后藤不会这样做的。您需要使用“继续”或“中断”进行执行控制。

您真的需要使用异常吗?@brenners1302我的观点是使用异常,并希望在点击后继续执行。为什么不将光标更改为仅选择id大于4的学生?哈哈,我问你是否真的需要一个异常,你回答你的观点是使用异常?然后你接受了一个不涉及异常使用的答案。
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;