识别多个Insert语句中的错误并回滚

问题描述 投票:0回答:1

我有一个场景,我必须插入 10 个表。代码如下所示:

create or replace procedure insert_into_tbls
as
begin
    savepoint s1;
    insert into tab1;
    insert into tab2;
    insert into tab3;
    insert into tab4;
    insert into tab5;
    savepoint s2;
    insert into tab6;
    insert into tab7;
    insert into tab8;
    insert into tab9;
    insert into tab10;
exception
    when others then
    dbms_output.put_line('Error Occurred');
    rollback to s1; -- or rollback to s2;
end

如果前5次插入出现错误,我想回滚到保存点s1。

如果插入表6-10出现错误,那么我想回滚到s2。

有没有办法判断错误是发生在前5次插入还是后5次插入?

这是面试时问我的。无法回答。

plsql rollback savepoints
1个回答
0
投票

您可以为此嵌套块

create or replace procedure insert_into_tbls
as
begin
  begin
    savepoint s1;
    insert into tab1;
    insert into tab2;
    insert into tab3;
    insert into tab4;
    insert into tab5;
 exception 
    when others then
      rollback to s1;
      return;
 end;
 begin
    savepoint s2;
    insert into tab6;
    insert into tab7;
    insert into tab8;
    insert into tab9;
    insert into tab10;
exception
    when others then
    rollback to s2;
end

但实际上,设置一个变量来指示您的进展可能会更容易(无论如何,这可能是调试工具的一部分)

要记住的另一件事是 PLSQL 调用隐式设置保存点,以便它们在逻辑上显示为单个工作单元,例如

SQL> create table t ( x int );

Table created.

SQL>
SQL> create or replace
  2  procedure p1 is
  3  begin
  4    insert into t values (1);
  5    insert into t values (2);
  6    insert into t values (3);
  7    insert into t values (4);
  8  end;
  9  /

Procedure created.

SQL>
SQL> create or replace
  2  procedure p2 is
  3    x int;
  4  begin
  5    insert into t values (5);
  6    insert into t values (6);
  7    insert into t values (7);
  8    insert into t values (8);
  9    x := 1/0;
 10  end;
 11  /

Procedure created.

SQL>
SQL> create or replace
  2  procedure p3 is
  3  begin
  4    p1;
  5    p2;
  6  end;
  7  /

Procedure created.

SQL>
SQL> exec p3;
BEGIN p3; END;

*
ERROR at line 1:
ORA-01476: divisor is equal to zero
ORA-06512: at "MCDONAC.P2", line 8
ORA-06512: at "MCDONAC.P3", line 4
ORA-06512: at line 1


SQL> select * from t;

no rows selected
© www.soinside.com 2019 - 2024. All rights reserved.