暂无图片
暂无图片
暂无图片
暂无图片
暂无图片

Oracle 在其他阶段删除末尾的记录

askTom 2017-09-18
209

问题描述

我有一个过程,每个在两个表中写一个记录。如果第二个表插入失败,希望删除插入第一个表的记录。但是,删除不会发生。问题是第二个表中的insert触发器有时会失败。这可能是过程的异常处理没有机会从第一个表中删除记录的原因吗?

有什么建议吗?

伪代码 (希望这清楚地定义了问题):

...

  insert into table_1 ( ...
  commit ;       -- Needed as this table's primary key is referenced as a foreign key by the second table
  v_flag_first_table_inserted := 'Y' ;    -- Initially set as 'n'

  insert into table_2 ( ...
  commit ;
  v_flag_second_table_inserted := 'Y' ;    -- Initially set as 'n'

  EXCEPTION
    when others then
    pr_internal_delete_first_table_if_needed ;
    raise_application_error ( ...

...
 
     pr_internal_delete_first_table_if_needed is begin  -- DEFINED EARLIER IN THE PROCEDURE
       if ( v_flag_first_table_inserted  = 'Y' and 
            v_flag_second_table_inserted = 'n' ) then
         delete table_1 where table_1_pk = ...
         commit:
       end if ;
     end ;
复制

专家解答

所以,如果你得到一个错误,你只想撤销插入之前?如果是这样,你就太复杂了!

您需要做的就是回滚。

或者,如果你是从客户那里打电话的,什么都没有。

由于语句级原子性,当引发异常时,Oracle数据库将回滚顶级调用完成的所有工作:

create table t1 (
  x int primary key
);
create table t2 (
  x int primary key
);

insert into t2 values (1);
commit;

select * from t1;

no rows selected

select * from t2;

X  
1  

create or replace procedure p ( p int ) as
begin
  insert into t1 values (p);  
  insert into t2 values (p);  
end p;
/

exec p(1);

ORA-00001: unique constraint (CHRIS.SYS_C0052933) violated

select * from t1;

no rows selected

select * from t2;

X  
1 
复制

「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。

评论