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