触发和约束冲突中的autonomous_transaction

问题描述:

我遇到了一个有趣的情况,用autonomous_transaction进行实验。考虑以下情况(请注意,它不打算这样写:概念恰恰证明):触发和约束冲突中的autonomous_transaction

create table t 
(
id int primary key, 
changed date 
) 
/

create or replace trigger t_trig 
before insert or update 
on t 
for each row 
declare 
    PRAGMA AUTONOMOUS_TRANSACTION; 
begin 
    :new.changed := sysdate; 
    commit; 
end; 
/

insert into t(id, changed) values (1, sysdate); 
insert into t(id, changed) values (2, sysdate); 

更改的日期的当前时间:

SQL> select * from t; 

     ID CHANGED 
--------- ----------------- 
     1 19.09.11 15:29:44 
     2 19.09.11 15:32:35 

让我们5秒打破然后执行以下操作:

update t set id = 2 where id = 1; 

很显然,这将失败,违反约束,但它不会改变changed属性,以及:

SQL> select * from t; 

     ID CHANGED 
--------- ----------------- 
     1 19.09.11 15:29:44 
     2 19.09.11 15:32:35 

我的问题是:为什么会发生这种情况?我确信我误解了一些基本概念,但我无法理解。

在此先感谢您的帮助。

PRAGMA AUTONOMOUS TRANSACTION保存上下文,打开另一个会话并创建一些内容。提交是必须的,否则这些更改将会丢失。您可以理解,只有在数据库中的某些块中所做的更改在此会话中才有意义(自治)。

所以,在你的触发器中,你什么都不做。 如果我们可以在这种模式下说出这个变量,:new.changed将在另一个会话中“更改”。它不会因您的更新而改变。