AT是由主事务(MT)调用但是独立于它的事务。当AT被调用时,mt被挂起,在AT的内部,一系列的dml可以被执行并且
commit或rollback.并且由于commit和rollback的独立性,他的commit和rollback并不影响mt的执行效果。在at结束执行之后
MT重新获得对事务的控制权
使用例子
--自治事务procedure
CREATEOR REPLACE PROCEDURE AUTO_PROCE IS
PRAGMAAUTONOMOUS_TRANSACTION; --其中pragma为预编译指令
BEGIN
INSERTINTO TEST VALUES ('autonomous!');
COMMIT;
END;
--非自治事务procedure
CREATEOR REPLACE PROCEDURE NOAUTO_PROCE IS
BEGIN
INSERTINTO TEST VALUES ('nonautonomous!');
COMMIT;
END--调用非自治事务
SQL> begin
2 insert into test values('test');
3 noauto_proce;
4 rollback;
5 end;
6 /
PL/SQL procedure successfully completed
SQL> select * from test;
M
------------------------------
nonautonomous!
nonautonomous!
nonautonomous!
test
nonautonomous!
可以看出,非自治事务中的commit影响到了主事务的执行,test也被一并commit,而之后的rollback不再起作用
--调用自治事务
SQL> truncate table test;
Table truncated
SQL> select 8 from test;
8
----------
SQL> begin
2 insert into test values('test1');
3 auto_proce;
4 rollback;
5 end;
6 /
PL/SQL procedure successfully completed
SQL> select * from test;
M
------------------------------
autonomous!
可以看出自治事务并没有影响到主事务的rollback.
--自治事务在日志记录中的应用
CREATE OR REPLACE PROCEDURE LOG_ERR(ERRINFO VARCHAR2) IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO TEST1_LOG VALUES (SYSDATE, ERRINFO);
COMMIT;
END;
CREATE OR REPLACE PROCEDURE INSERT_TEST(NUMID NUMBER, MSG VARCHAR2) IS
BEGIN
INSERT INTO TEST1 (NUMID, MSG);
COMMIT;
END;
DECLARE
BEGIN
INSERT_TEST(1, 'testtest');
INSERT_TEST(2, 'test');
EXCEPTION
WHEN OTHERS THEN
LOG_ERR(DBMS_UTILITY.FORMAT_ERROR_BACKTRACE);
RAISE;
END;