0
点赞
收藏
分享

微信扫一扫

利用自治事务技术写一个用于审计的触发器



自治事务:它是被一个事务调用的事务,但它独立于它的父事务提交或回滚。一般会被用于:

a   匿名块

b   本地、对立或打包的函数或过程

c   对象类型的方法

d   触发器

实验注意:


所有操作都使用非SYS用户(DBA或普通用户)。

在SYS用户下做,会报:

第 1 行出现错误:

ORA-04089: 无法对 SYS 拥有的对象创建触发器


建表:


18:42:13 SQL> create table test(id int,name varchar2(20),num int,cost int);


Table created


18:43:46 SQL>


写触发器,

update on test 会触发写审计信息。


18:44:11 SQL> create or replace trigger tib_test

after update on test for each row


declare


pragma autonomous_transaction;


tib_id number;


tib_name varchar2(20);


tib_remain_num number;


tib_cost number;


begin


tib_id :=old.id;


tib_name :=:new.name;


tib_remain_num :=:new.num;


tib_cost :=:new.cost;


insert into test_audit values (tib_id,tib_name,tib_remain_num,tib_cost);


commit;


end;


 /



Trigger created


插入数据:


18:45:54 SQL> insert into test values(4,'apple-4',40,4000);


1 row inserted


18:46:47 SQL> insert into test values(4,'apple-4',40,4000);


1 row inserted


18:47:08 SQL> insert into test values(3,'apple-3',30,3000);


1 row inserted


18:47:25 SQL> update test set num=38,cost=999 where id=3;


1 row updated


18:47:36 SQL> update test set num=38,cost=999 where id=4;


2 rows updated


18:47:38 SQL> select * from test;


        ID NAME                        NUM       COST


---------- -------------------- ---------- ----------


         4 apple-4                      38        999


         4 apple-4                      38        999


         3 apple-3                      38        999



可以查看到,更新时产生的审计信息,插入操作时没有产生。

18:47:43 SQL> select * from test_audit;


        ID NAME                                              REMAIN_NUM       COST


---------- -------------------- --------------------------------------- ----------


         3 apple-3                                                   38        999


         4 apple-4                                                   38        999


         4 apple-4                                                   38        999



回滚事务,触发器中写入审计的信息已经提交,不受影响。


18:47:53 SQL> rollback;


Rollback complete


18:48:05 SQL> select * from test;


        ID NAME                        NUM       COST


---------- -------------------- ---------- ----------



18:48:08 SQL> select * from

test_audit;


        ID NAME                                              REMAIN_NUM       COST


---------- -------------------- --------------------------------------- ----------


         3 apple-3                                                   38        999


         4 apple-4                                                   38        999


         4 apple-4                                                   38        999


举报

相关推荐

0 条评论