Reputation: 3200
I need to create a trigger that writes changes in a shadow table. I know how to create the trigger but my challenge is that I need the records in the new table to exist even after a rollback.
This is an example of how the output will look like
INSERT INTO department VALUES (95, 'PURCHASING', 'CHICAGO');<br>
ROLLBACK;
1 rows inserted.
rollback complete.
SELECT * FROM department_log;
DEPARTMENT_ID DEPARTMENT_NAME ADDRESS OPERATION_TIME
---------------------- -------------------- -------------------- ------------------
90 HR CHICAGO 03-NOV-11
95 PURCHASING CHICAGO 03-NOV-11
SELECT * from department WHERE department_id >= 90;
DEPARTMENT_ID DEPARTMENT_NAME ADDRESS
---------------------- -------------------- --------------------
90 HR CHICAGO
Upvotes: 2
Views: 1287
Reputation: 231741
You'll need to use autonomous transactions.
SQL> create table t (col1 number);
Table created.
SQL> create table t_shadow( col1 number, dt date );
Table created.
SQL> create trigger trg_t
2 before insert on t
3 for each row
4 declare
5 pragma autonomous_transaction;
6 begin
7 insert into t_shadow( col1, dt )
8 values( :new.col1, sysdate );
9 commit;
10 end;
11 /
Trigger created.
SQL> insert into t values( 1 );
1 row created.
SQL> rollback;
Rollback complete.
SQL> select * from t;
no rows selected
SQL> select * from t_shadow;
COL1 DT
---------- ---------
1 09-NOV-11
Note that if you find yourself using autonomous transactions for anything other than persistent logging, you are almost certainly doing something wrong. Autonomous transactions are a very dangerous and very frequently misused feature.
Upvotes: 6
Reputation: 27294
You would need to declare the trigger as an Autonomous Transaction
PRAGMA AUTONOMOUS_TRANSACTION;
This decouples the trigger code from the main transaction, so even if the main insertion into the table (which fired the trigger) rollsback, the trigger is executed in a different transactional context and can commit / rollback independently.
Upvotes: 2