Oracle 临时表详解(temporary table)

1 概述

1. 作用:用来 '临时' 存储数据
   (1) 当一个事务或会话结束的时候,这个临时表中的 '数据' 会被数据库自动清空
   (2) 但 '表结构' 依旧保留
   
2. 分类: '生命周期的不同'
   (1) 事务级临时表: on commit delete rows;   commit'删除' 记录(默认)
   (2) 会话级临时表: on commit preserve rows; commit'保存' 记录,结束会话时 '删除' 记录

3. 注意
   (1) 临时表处理的效率高于普通表
       <1> 不记录 '日志'
       <2> 只能当前用户使用,不会产生 ''
   (2) 和普通表操作方式一样

4. 以下测试中,创建临时表后,信息查询
   select t.owner,
          t.table_name,
          t.tablespace_name, -- 所属表空间
          t.logging, -- 是否记录日志
          t.duration --生命周期
     from dba_tables t
    where t.owner = 'SCOTT'
      and t.table_name in ('TRANSACTION_TEMP', 'SESSION_TEMP');

2 分类

2.1 事务级临时表

create global temporary table transaction_temp (
  tid   number(3),
  tname varchar2(30)
) on commit delete rows; -- on commit delete rows 可省略(默认)

验证:事务中,数据可以查询,事务结束后(commit、rollback)后,数据被清空

insert into transaction_temp(tid, tname) values(1, 'a');
insert into transaction_temp(tid, tname) values(2, 'b');
-- commit;

select * from transaction_temp;

查询截图:

2.2 会话级临时表

create global temporary table session_temp (
   tid   number(3),
   tname varchar2(30)
) on commit preserve rows;

验证:commit 时,保存数据至表中,会话结束后,数据被清空

insert into session_temp(tid, tname) values(1, 'a');
insert into session_temp(tid, tname) values(2, 'b');
commit;

select * from session_temp;

结束会话有以下办法:(上述测试,立马就结束了,执行很快哦)

1. 自然结束(执行完成) -- sql_text => begin :id := sys.dbms_transaction.local_transaction_id; end;
   select t1.sid, t1.serial#, t2.sql_text, t2.action
     from v$session t1, v$sql t2
    where t2.sql_id = t1.prev_sql_id
      and t1.username = 'SCOTT';
  
2. 手动删除
   (1) alter system kill session 'sid,serial#';

再新建一个会话,查询:数据被清空了

好的代码像粥一样,都是用时间熬出来的
原文地址:https://www.cnblogs.com/jijm123/p/15366969.html