ORACLE的临时表在应用系统中有很大的作用,它可以让用户只能够操作各自的数据中而互不干扰,不用担心会破坏或影响其他SESSION/TRANSACTION的数据,这也是数据安全的一种解决方法
临时表分为SESSION、TRANSACTION两种,SESSION级的临时表数据在整个SESSION都存在,直到结束此次SESSION;而TRANSACTION级的临时表数据在TRANACTION结束后消失,即COMMIT/ROLLBACK或结束SESSION都会清除TRANACTION临时表数据。
两种临时表的语法:
create global temporary table 临时表名 on commit preserve|delete rows
用preserve时就是SESSION级的临时表,用delete就是TRANSACTION级的临时表
1、session临时表
SQL> create global temporary table t_tmp_session
2 (id varchar2(10),
3 name varchar2(16))
4 on commit preserve rows;
Table created
SQL> insert into t_tmp_session values('001','sqlee');
1 row inserted
SQL> commit;
Commit complete
SQL> select *from t_tmp_session;
ID NAME
---------- ----------------
001 sqlee
commit后select发现数据还在,断开该session再select结果如下:
SQL> conn sys/sys as sysdba;
Connected to Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
Connected as SYS
SQL> conn sqlee/sqlee;
Connected to Oracle Database 10g Enterprise Edition Release 10.2.0.1.0
Connected as sqlee
SQL> select *from t_tmp_session;
ID NAME
---------- ----------------
现在发现临时表的数据已经不在了,这就是session级的临时表,session结束会清除数据。
2、TRANACTION临时表
SQL> create global temporary table t_tmp_tranaction
2 (id varchar2(10),
3 name varchar2(16))
4 on commit delete rows;
Table created
SQL> insert into t_tmp_tranaction values('001','sqlee');
1 row inserted
SQL> select *from t_tmp_tranaction;
ID NAME
---------- ----------------
001 sqlee
SQL> commit;
Commit complete
SQL> select *from t_tmp_tranaction;
ID NAME
---------- ----------------
这就是tranaction级临时表,commit之后清除数据。
3、用as子句创建tranaction临时表
SQL> select * from t_tmp_session;
ID NAME
---------- ----------------
001 sqlee
SQL> create global temporary table t_tmp_tranaction_as on commit delete rows
2 as select *from t_tmp_session
3 ;
Table created
SQL> select *from t_tmp_tranaction_as;
ID NAME
---------- ----------------
因为create table.....as select ....是自动commit的,所以该表也没数据。