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

时间:2016-04-13 06:52:11

标签: 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
        <<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

3 个答案:

答案 0 :(得分:3)

ng-model="$parent.client.providersList.id"中使用goto时,光标将被关闭,因此无法达到预期的行为。

来自Doc

  

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

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

exit

答案 1 :(得分:1)

如果可以,您应该避免在任何代码中使用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;

答案 2 :(得分:1)

你真的应该选择id&gt; 4来避免异常。

Goto不会这样工作。您需要使用continue或break来执行控制。