Đây có thể là một trong những trường hợp hiếm hoi khi bạn có thể sử dụng pragma autonomous_transaction . Nó sẽ cho phép bạn cam kết mà không ảnh hưởng đến giao dịch chính của bạn. Sử dụng nó một cách thận trọng. Tìm hiểu thêm về giao dịch tự trị
và self_transaction pragma
Đây là một ví dụ:
-- our error logging table
create table tb_log(
msg varchar2(123)
)
/
-- our working table
create table tb_table(
col11 number
)
/
-- procedure that is going to log errors
example@sqldat.com> create or replace procedure log_error(p_msg in varchar2)
2 is
3 pragma autonomous_transaction;
4 begin
5 insert into tb_log(msg)
6 values(p_msg);
7 commit;
8 end;
example@sqldat.com> /
Procedure created.
example@sqldat.com> create or replace trigger tr_tb_table
2 before insert on tb_table
3 for each row
4 begin
5 if mod(:new.col1, 2) != 0
6 then
7 log_error('Error!');
8 raise_application_error(-20000, 'Error has ocurred!');
9 end if;
10 end;
11 /
Trigger created.
example@sqldat.com> select * from tb_log;
no rows selected
example@sqldat.com> select * from tb_table;
no rows selected
example@sqldat.com> insert into tb_table(col1) values(1);
insert into tb_table(col1) values(1)
*
ERROR at line 1:
ORA-20000: Error has ocurred!
ORA-06512: at "NK.TR_TB_TABLE", line 5
ORA-04088: error during execution of trigger 'NK.TR_TB_TABLE'
example@sqldat.com> select * from tb_log;
MSG
--------------------------------------------------------------------------------
Error!