Oracle臨時表的創建與使用
臨時表存儲事務或會話的中間結果集,臨時表中保存的數據只對當前會話可見。臨時表不存在併發行爲,因爲他們對於當前會話都是獨立的。oracle中的臨時表分爲會話級臨時表和事務級別臨時表。
一、會話級臨時表
會話級臨時表是指臨時表中的數據只在會話生命週期之中存在,當用戶退出會話的時候,Oracle自動清除臨時表中數據。創建會話級臨時表的語法如下:
create global temporary table 臨時表名稱
......
on commit preserve rows;
1、創建會話級臨時表
SQL>
create global temporary table tmp001 on commit preserve rows
as select * from emp where deptno=30;
2、查看臨時表中的數據
SQL> select * from tmp001;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
6 rows selected.
會話級臨時表當結束事務時其中的數據不會受到影響,但在另一個會話中看不到臨時表中的數據,驗證如下:
(1)執行commit命令,臨時表數據不受影響
SQL> commit;
Commit complete.
SQL> select * from tmp001;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30
7521 WARD SALESMAN 7698 22-FEB-81 1250 500 30
7654 MARTIN SALESMAN 7698 28-SEP-81 1250 1400 30
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7844 TURNER SALESMAN 7698 08-SEP-81 1500 0 30
7900 JAMES CLERK 7698 03-DEC-81 950 30
6 rows selected.
(2)打開另一個會話,查詢數據
SQL> conn scott/tiger
Connected.
SQL> select * from tmp001;
no rows selected
二、事務級臨時表
事務級臨時表是指臨時表中的數據只在事務生命週期中存在。當一個事務結束(commit or rollback),Oracle自動清除臨時表中數據。
創建事務級臨時表的語法如下:
create global temporary table 臨時表名稱
......
on commit delete rows;
說明:如果省略on commit delete rows參數,默認創建的也是事務級臨時表。
1、創建事務級臨時表
臨時表temp01和temp02都是事務級臨時表。
SQL> create global temporary table temp001 on commit delete rows
as select * from emp where deptno=10;
Table created.
SQL> create global temporary table temp002
as select empno,ename,sal,comm from emp;
Table created.
2、查看臨時表數據
查詢發現,兩個臨時表中都沒有數據,原因是ddl語句會自動commit,所以會清空臨時表的數據。
SQL> select * from temp001;
no rows selected
SQL> select * from temp002;
no rows selected
3、向臨時表插入數據
SQL> insert into temp001 select * from emp where sal>2000;
6 rows created.
SQL> select * from temp001;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- --------- ---------- ---------- ----------
7566 JONES MANAGER 7839 02-APR-81 2975 20
7698 BLAKE MANAGER 7839 01-MAY-81 2850 30
7782 CLARK MANAGER 7839 09-JUN-81 2450 10
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7839 KING PRESIDENT 17-NOV-81 5000 10
7902 FORD ANALYST 7566 03-DEC-81 3000 20
6 rows selected.
4、結束事務,查看臨時表數據
如果使用commit或rollback結束事務,則會清空臨時表的數據。
SQL> rollback;
Rollback complete.
SQL> select * from temp001;
no rows selected