之前認為 create table xxx as select * from table...不就可以馬上產生出一個臨時可以用的table嗎?

但若是同一個程式多人同時執行,將產生的table暫存用,裡面混著使用實在不是好方法,其實oracle有產生暫存Table的作法。

Oracle暫存Table是以session來產生跟刪除資料的,也就是同一個程式不同程式產生暫存Table,這些Table都是獨立的放在Temporary Tablespace,最晚每次transcation結束就會清除table內的所有資料,程式設計人員無需擔心資料的處理。

The CREATE GLOBAL TEMPORARY TABLE statement creates a temporary table.
You can create indexes, views, and triggers on temporary tables,
and you can also use Export and
Import or Data Pump to export and import the definition of a temporary table.
However, no data is exported, even if you use the ROWS option.

 

以下是簡介 跟 範例:


語法:

CREATE GLOBAL TEMPORARY TABLE tempname


配合下面兩個選項
ON COMMIT DELETE ROWS:
   To specify that the lifetime of the inserted rows is for
   the duration of the transaction only

ON COMMIT PRESERVE ROWS:
   To specify that the lifetime of the inserted rows is
   for the duration of the session


範例:(僅transcation方式測試)

CREATE GLOBAL TEMPORARY TABLE employees_tmp
ON COMMIT DELETE ROWS
as select * from employees;

--新增資料到employees_tmp
insert into employees_tmp
select * from employees where employee_id = '113';


--看一下資料是有進去
select * from employees_tmp ;

--這時候可以來做一些處理

--處理完畢,commit表示transcation結束
commit;

--看一下資料不見了
select * from employees_tmp ;

--若需求是這個session結束才刪除,則指令為 ON COMMIT PRESERVE ROWS

 

後記:

在之後程式設計中,發現在程式處理階段,web程式對於連結一個oracle session有時會延續一段時間,假設這時程式發生了一些Exception,除非ap程式中斷與oracle連線,否則暫存資料會像被lock住一樣無法增刪修,進退兩難,求生不能求死不得。

我個人解決方式為使用暫存Table需搭配try finally 機制,結束後就finally 段使用truncate table 刪除TEMPORARY TABLE資料。

arrow
arrow
    全站熱搜

    味味A 發表在 痞客邦 留言(0) 人氣()