日期:2014-05-16 浏览次数:20477 次
1、什么是Oracle自治事务
在官方文档中,是这样的定义的“Autonomous transactions are independent transactions that can be called from within another transaction.”就是说它被一个事务调用的事务,但它独立于它的父事务提交或回滚。
下面看一个例子
首先创建一张测试表
MIKE@ORA11G> create table test(m varchar2(30)); Table created.
创建两个procedure,一个是自治事务的,一个是非自治事务的
create or replace procedure auto_proce
as
pragma autonomous_transaction;
begin
insert into test values('autonomous!');
commit;
end;
/
create or replace procedure nonauto_proce
as
begin
insert into test values('nonautonomous!');
commit;
end;
/
SQL> select * from test;
未选定行
SQL> begin
2 insert into test values('test');
3 nonauto_proce;
4 rollback;
5 end;
6 /
PL/SQL 过程已成功完成。
SQL> select * from test;
M
------------------------------
test
nonautonomous!
下面再看一下auto_proce的情况。
SQL> truncate table test;
表被截断。
SQL> select * from test;
未选定行
SQL> begin
2 insert into test values('test1');
3 auto_proce;
4 rollback;
5 end;
6 /
PL/SQL 过程已成功完成。
SQL> select * from test;
M
------------------------------
autonomous!
通过这个例子,可以看出自治事务对其父事务并不会造成任何影响。
自治事务一般会被用于:
a 匿名块
b 本地、对立或打包的函数或过程
c 对象类型的方法
d 触发器
2、自治事务与父事务(调用者)的关系
创建一个过程,在commit前休眠10秒,以便查看系统中的一些信息。
create or replace procedure auto_p1
as
pragma AUTONOMOUS_TRANSACTION;
begin
insert into test values('test2');
dbms_lock.sleep(10);
commit;
end;查看会话的SID(会话A)
SQL> conn sys/admin as sysdba
已连接。
SQL> select sid from v$mystat where rownum=1;
SID
----------
144通过sqlplus打开另一个连接(会话B),查看会话信息
SQL> select sid, username, status from v$session;
SID USERNAME STATUS
---------- ------------------------------ --------
138 ACTIVE
143 SYS INACTIVE
144 SYS INACTIVE
145 SYS INACTIVE
147 SYS ACTIVE
149 ACTIVE
151 ACTIVE
157 ACTIVE
159 ACTIVE
160 ACTIVE
161 ACTIVE
SQL> begin 2 auto_p1; 3 end; 4