SET TRANSACTION READ ONLY實際上是實現數據庫四大事務(ACID)中隔離性(Isolation)的一種手段,用來將數據的讀一致性定在某一時間點,即不管其他事務如何更改數據(不能在當前session中再使用自治事務),在當前事務中進行查詢的結果始終不變。由於Oracle的讀一致性是通過undo段來實現的,所以如果在此期間DML修改的數據量很大而undo空間設置過小可能會導致ORA-01555(快照過舊)錯誤。
Test Code:
Step 1, @session 1(SET TRANSACTION READ ONLY):
- Connected to Oracle Database 11g Enterprise Edition Release 11.2.0.1.0
- Connected as tuser1
- SQL> select * from dept;
- DEPTNO DNAME LOC
- ------ -------------- -------------
- 10 ACCOUNTING NEW YORK01
- 20 RESEARCH DALLAS
- 30 SALES CHICAGO
- 40 OPERATIONS BOSTON
- SQL> SET TRANSACTION READ ONLY;
- Transaction set
Step 2, @session 2(DML, insert a new record):
- SQL> select * from dept;
- DEPTNO DNAME LOC
- ------ -------------- -------------
- 10 ACCOUNTING NEW YORK01
- 20 RESEARCH DALLAS
- 30 SALES CHICAGO
- 40 OPERATIONS BOSTON
- SQL> insert into dept(deptno) values(50);
- 1 row inserted
- SQL> commit;
- Commit complete
- SQL> select * from dept;
- DEPTNO DNAME LOC
- ------ -------------- -------------
- 10 ACCOUNTING NEW YORK01
- 20 RESEARCH DALLAS
- 30 SALES CHICAGO
- 40 OPERATIONS BOSTON
- 50
Step 3, @session 1(query the same object and get the same result):
- SQL> select * from dept;
- DEPTNO DNAME LOC
- ------ -------------- -------------
- 10 ACCOUNTING NEW YORK01
- 20 RESEARCH DALLAS
- 30 SALES CHICAGO
- 40 OPERATIONS BOSTON
Step 4, @session 1(autonomous transaction is not permitted):
- SQL> declare
- 2 pragma AUTONOMOUS_TRANSACTION;
- 3 begin
- 4 update dept set loc = loc || '-XXX' where deptno=20;
- 5 end;
- 6 /
- declare
- pragma AUTONOMOUS_TRANSACTION;
- begin
- update dept set loc = loc || '-XXX' where deptno=20;
- end;
- ORA-06519: active autonomous transaction detected and rolled back
- ORA-06512: at line 6
- SQL> select * from dept;
- DEPTNO DNAME LOC
- ------ -------------- -------------
- 10 ACCOUNTING NEW YORK01
- 20 RESEARCH DALLAS
- 30 SALES CHICAGO
- 40 OPERATIONS BOSTON
- SQL>
Step 5, @session 1(commit current transaction and we get the change):
- SQL> commit;
- Commit complete
- SQL> select * from dept;
- DEPTNO DNAME LOC
- ------ -------------- -------------
- 10 ACCOUNTING NEW YORK01
- 20 RESEARCH DALLAS
- 30 SALES CHICAGO
- 40 OPERATIONS BOSTON
- 50