Dette kan være et af de sjældne tilfælde, hvor du kan bruge pragma autonomous_transaction
. Det giver dig mulighed for at forpligte dig uden at påvirke din hovedtransaktion. Brug det med forsigtighed. Få mere at vide om autonome transaktioner
og autonom_transaction pragma
Her er et eksempel:
-- 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
[email protected]> 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;
[email protected]> /
Procedure created.
[email protected]> 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.
[email protected]> select * from tb_log;
no rows selected
[email protected]> select * from tb_table;
no rows selected
[email protected]> 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'
[email protected]> select * from tb_log;
MSG
--------------------------------------------------------------------------------
Error!