临时表:
临时性,值得是所存储数据的临时性。也就是说,临时表虽然一直存在,但是其中的数据会在某种条件下被oracle数据库自动清空。
临时表清空数据库的条件有两个:一是事务提交或回滚,二是会话结束。
每个事务是指从上一次执行从commit,到本次执行commit之间的操作。换言之,被commit或rollback包围的所有数据库操作就是一个事务。
Oracle中的会话是指每个与用户进行交互的进程。在PLSQL developer中,每次打开一个新的【SQL window】或者【Command window】时,将建立一个新的会话。
对应临时表清空数据的时机,临时表分为两类:事务级临时表和会话级临时表。事务级临时表是指当事务提交或事务回滚时。表中数据将被清空。会话级临时表是指当会话结束时,表中数据被清空,并且同一时刻,两个不同会话无法访问彼此的数据
会话级临时表:
SQL> create global temporary table tmp_users_session(user_id int,user_name varchar2(20)) on commit preserve rows;
Table created
SQL> desc tmp_users_session;
Name Type Nullable Default Comments
--------- ------------ -------- ------- --------
USER_ID NUMBER(38) Y
USER_NAME VARCHAR2(20) Y
SQL> insert into tmp_users_session(user_id,user_name) values(1,'ll');
1 row inserted
SQL> insert into tmp_users_session(user_id,user_name) values(2,'zb');
1 row inserted
SQL> select * from tmp_users_session;
USER_ID USER_NAME
--------------------------------------- --------------------
1 ll
2 zb
SQL> commit;
Commit complete
重新打开一个命令窗口,在该窗口中查询tmp_users_session表中的数据
SQL> select * from tmp_users_session;
USER_ID USER_NAME
--------------------------------------- --------------------
SQL>
表中的数据不存在了,但是表还是存在的
SQL> desc tmp_users_session;
Name Type Nullable Default Comments
--------- ------------ -------- ------- --------
USER_ID NUMBER(38) Y
USER_NAME VARCHAR2(20) Y
SQL>
事务级临时表:
SQL> create global temporary table tmp_users_transaction (user_id int,user_name varchar2(20)) on commit delete rows;
Table created
SQL> desc tmp_users_transaction;
Name Type Nullable Default Comments
--------- ------------ -------- ------- --------
USER_ID NUMBER(38) Y
USER_NAME VARCHAR2(20) Y
SQL> insert into tmp_users_transaction (user_id,user_name) values(1,'ll');
1 row inserted
SQL> insert into tmp_users_transaction(user_id,user_name) values(2,'zb');
1 row inserted
SQL> select * from tmp_users_transaction;
USER_ID USER_NAME
--------------------------------------- --------------------
1 ll
2 zb
SQL> commit;
Commit complete
SQL> select * from tmp_users_transaction;
USER_ID USER_NAME
--------------------------------------- --------------------
SQL> insert into tmp_users_transaction (user_id,user_name) values(1,'ll');
1 row inserted
SQL> insert into tmp_users_transaction(user_id,user_name) values(2,'zb');
1 row inserted
SQL> select * from tmp_users_transaction;
USER_ID USER_NAME
--------------------------------------- --------------------
1 ll
2 zb
SQL> rollback;
Rollback complete
SQL> select * from tmp_users_transaction;
USER_ID USER_NAME
--------------------------------------- --------------------
SQL>