您的位置:首页 > 数据库 > Oracle

Oracle的自治事务

2017-01-03 13:15 429 查看
自治事务(autonomous transaction)允许你创建一个"事务中的事务",它能独立于其父事务提交或回滚。利用自治事务,可以挂起当前执行的事务,开始一个新事务,完成一些工作,然后提交或回滚,所有这些都不影响当前所执行事务的状态。自治事务提供了一种用PL/SQL控制事务的新方法,可用于:
顶层匿名块;

本地(过程中的过程)、独立或打包的函数和过程;

对象类型的方法;

数据库触发器。

使用例子演示自治事务如何工作
--创建测试表用于保存信息
zx@ORCL>create table t ( msg varchar2(25) );

Table created.
--创建自治事务的存储过程
zx@ORCL>create or replace procedure Autonomous_Insert
2  as
pragma autonomous_transaction;---指示自治事务语句
4  begin
5          insert into t values ( 'Autonomous Insert' );
6          commit;
7  end;
8  /

Procedure created.
--创建普通存储过程
zx@ORCL>create or replace procedure NonAutonomous_Insert
2  as
3  begin
4          insert into t values ( 'NonAutonomous Insert' );
5          commit;
6  end;
7  /

Procedure created.
观察使用PL/SQL代码中非自治事务的行为
zx@ORCL>begin
2          insert into t values ( 'Anonymous Block' );
3          NonAutonomous_Insert;
4          rollback;
5  end;
6  /

PL/SQL procedure successfully completed.

zx@ORCL>select * from t;

MSG
---------------------------------------------------------------------------
Anonymous Block
NonAutonomous Insert
可以观察到非自治事务的过程中的commit也把调用它的父事务也提交了,而父事务中的rollback没有起到作用。
再观察使用PL/SQL代码中非自治事务的行为
zx@ORCL>delete from t;

2 rows deleted.

zx@ORCL>commit;

Commit complete.

zx@ORCL>begin
insert into t values ( 'Anonymous Block' );
Autonomous_Insert;
rollback;
end;
6  /

PL/SQL procedure successfully completed.

zx@ORCL>select * from t;

MSG
---------------------------------------------------------------------------
Autonomous Insert
可以看到,自治事务过程中的commit只把它本身的事务提交了,而对于父事务的语句没有起到作用,而父事务中的rollback对自治事务中的语句也没有作用。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Oracle 事务 自治