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#';

再新建一個會話,查詢:數據被清空了

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM