Oracle中的触发器以及如何在回滚后保留记录

Geo*_*Geo 2 oracle triggers oracle10g

我需要创建一个在影子表中写入更改的触发器.我知道如何创建触发器但我的挑战是我需要新表中的记录即使在回滚后仍然存在.

这是输出结果的示例

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
Run Code Online (Sandbox Code Playgroud)

Jus*_*ave 6

您需要使用自治事务.

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
Run Code Online (Sandbox Code Playgroud)

请注意,如果您发现自己使用自治事务而不是持久性日志记录,那么您几乎肯定会做错事.自治交易是一种非常危险且经常被滥用的功能.