一、什么是临时表
Oracle的临时表只在事务(transaction)或者会话(session)期间保持数据。临时表中的数据对于会话(session)来说是私有的,这意味这每个会话只能查看和修改自己的数据。
对于应用程序而言,临时表对于一些需要暂时缓存的数据是非常有用的。
二、创建临时表
CREATE GLOBAL TEMPORARY TABLE语句创建一个临时表。子句ON COMMIT表示是否是事务级别或者会话级别,默认是事务级别。可以为临时表创建索引。为临时表创建的索引也是临时的。临时表上创建的索引与表具有相同的级别。
三、实验部分
实验环境:
-
SQL> select * from v$version;
-
-
BANNER
-
----------------------------------------------------------------
-
Oracle Database 10g Enterprise Edition Release 10.2.0.4.0 - 64bi
-
PL/SQL Release 10.2.0.4.0 - Production
-
CORE 10.2.0.4.0 Production
-
TNS for Linux: Version 10.2.0.4.0 - Production
-
NLSRTL Version 10.2.0.4.0 - Production
事务级别的临时表:
-
SQL> create global temporary table t_trans
-
2 ( id number)
-
3 on commit delete rows;
-
-
Table created.
插入语句:
-
SQL> insert into t_trans values(1);
-
-
1 row created.
查询
-
SQL> select * from t_trans;
-
-
ID
-
----------
-
1
显示提交并查询
-
SQL> commit;
-
-
Commit complete.
-
-
SQL> select * from t_trans;
-
-
no rows selected
重新插入数据,隐式提交,并查询
-
SQL> insert into t_trans values(1);
-
-
1 row created.
-
-
SQL> create table t100(id number);
-
-
Table created.
-
-
SQL> select * from t_trans;
-
-
no rows selected
通过上面的实验我们不难验证基于事务的临时表当事务结束是,表里面的数据会清空。
会话级别的临时表:
创建临时表:
-
SQL> create global temporary table t_session
-
2 (id number)
-
3 on commit preserve rows;
-
-
Table created.
插入语句,提交,查询:
-
SQL> insert into t_session values(1);
-
-
1 row created.
-
-
SQL> commit;
-
-
Commit complete.
-
-
SQL> select * from t_session;
-
-
ID
-
----------
-
1
用另外一个session查询:
-
SQL> select * from t_session;
-
-
no rows selected
另外一个session并没有查到数据。
不显示指定ON COMMIT:
-
SQL> create global temporary table t_100
-
2 (id number);
-
-
Table created.
-
-
SQL> insert into t_100 values(100);
-
-
1 row created.
-
-
SQL> commit;
-
-
Commit complete.
-
-
SQL> select * from t_100;
-
-
no rows selected
与事务级别的效果相同,提交后表中没有数据。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29173997/viewspace-1164686/
,如需转载,请注明出处,否则将追究法律责任。