
Oracle触发器内部抛出异常怎样让它插入的数据不回滚?

SQL> create table tb1 (id varchar2(5) primary key);
Table created
SQL> create table tb2 (id varchar2(4));
Table created
注意tb2的id字段宽度比tb1的要少1。
建立触发器:
create or replace trigger "TR_TB1_INSERT"
after insert on tb1 for EACH ROW
begin
insert into tb2 values (:new.id);
end;
/
tb1插入4个字符,不报错,触发器正常运行:
SQL> insert into tb1 values ('ABCD');
1 row inserted
SQL> commit;
Commit complete
SQL> select * from tb2;
ID
----
ABCD
tb1插入5个字符, 报错,触发器未能正常运行:
SQL> insert into tb1 values ('EFGHI');
insert into tb1 values ('EFGHI')
ORA-12899: value too large for column "XXX"."TB2"."ID" (actual: 5, maximum: 4)
ORA-06512: at "XXX.TR_TB1_INSERT", line 2
ORA-04088: error during execution of trigger 'XXX.TR_TB1_INSERT'
SQL> select * from tb1;
ID
-----
ABCD
SQL> select * from tb2;
ID
----
ABCD
改写触发器,加入异常处理:
create or replace trigger "TR_TB1_INSERT"
after insert on tb1 for EACH ROW
begin
insert into tb2 values (:new.id);
exception
when others then
null;
end;
tb1插入5个字符,不再报错,但触发器未能实现其功能,即tb2未插入相应记录:
SQL> insert into tb1 values ('JKLMN');
1 row inserted
SQL> commit;
Commit complete
SQL> select * from tb2;
ID
----
ABCD
SQL> select * from tb1;
ID
-----
ABCD
JKLMN


触发器用before,然后调用带自治事务的存储过程


