Oracle创建临时表

来源:互联网 发布:安知我意txt 编辑:程序博客网 时间:2024/06/05 08:43

1.创建一个临时表emp_temp
SQL> create global temporary table
  2  scott.emp_temp
  3  on commit preserve rows
  4  as
  5  select * from scott.emp
  6  where job not like 'SAL%';

Table created.

临时表中存储的是会话私有数据,这些数据只有在事务进行或会话期间存在。
通过on commit delete rows 或on commit preserve rows子句来控制数据存在的周期。
其中:
on commit delete rows:说明数据行只有在事务中可见,也是默认值。
on commit preserve rows:说明数据行在整个会话中可见。

每一个会话只能看到和修改它自己的数据,因此在临时表的数据下不需要也没有DML锁。

例如:

在当前会话下查询:
SQL> select empno,ename,job,sal,deptno from scott.emp_temp;

     EMPNO ENAME      JOB              SAL     DEPTNO
---------- ---------- --------- ---------- ----------
      7369 SMITH      CLERK            800         20
      7566 JONES      MANAGER         2975         20
      7698 BLAKE      MANAGER         2850         30
      7782 CLARK      MANAGER         2450         10
      7788 SCOTT      ANALYST         3000         20
      7839 KING       PRESIDENT       5000         10
      7876 ADAMS      CLERK           1100         20
      7900 JAMES      CLERK            950         30
      7902 FORD       ANALYST         3000         20
      7934 MILLER     CLERK           1300         10

10 rows selected.


使用scott用户登录查询:

SQL> conn scott/tiger
Connected.
SQL> select empno,ename,job,sal,deptno from emp_temp;

no rows selected

查询结果显示:可以看出在scott用户下不能看到在system用户中所创建的临时表emp_temp中的数据。即使再以system用户登录,也无法看到临时表emp_temp中的数据。

想普通表一样,也可以在临时表上创建索引。视图和触发器。甚至可以使用导出和导入程序对临时表的定义进行导出和导入。但是无法导出临时表中的数据。
 
  与永久表不同的是临时表并不使用用户的默认表空间而是使用临时段。我们可以查询验证一下:

SQL> select table_name,tablespace_name,temporary from user_tables;

TABLE_NAME                     TABLESPACE_NAME                T
------------------------------ ------------------------------ -
DEPT                           USERS                          N
EMP                            USERS                          N
BONUS                          USERS                          N
SALGRADE                       USERS                          N
STUDENT                        USERS                          N
PRODUCT                        USERS                          N
EMP_TEMP                                                      Y

7 rows selected.

查询表明:emp_temp为临时表,最后的一列值:Y,而且该表也没有存放在scott用户的默认表空间users中。