1. 程式人生 > >在oracle儲存過程中建立臨時表

在oracle儲存過程中建立臨時表

在oracle的儲存過程中,不能直接使用DDL語句,比如create、alter、drop、truncate等。

那如果我們想在儲存過程中建立一張臨時表就只能使用動態sql語句了:

create or replace procedure pro as
  str_sql varchar2(100);
begin
  -- 建立臨時表
  str_sql := 'create global temporary table temp_table (
       col1 varchar2(10),
       col2 number
    ) on commit preserve rows';
  execute immediate str_sql;

  -- 使用臨時表
  str_sql := 'insert into temp_table(col1, col2) values(''a'', 1)';
  execute immediate str_sql;

  -- 刪除臨時表
  str_sql := 'drop table temp_table';
  execute immediate str_sql;
end;

在oracle中,臨時表分為會話級別(session)和事務級別(transaction)兩種。

會話級的臨時表在整個會話期間都存在,直到會話結束;事務級別的臨時表資料在transaction結束後消失,即commit/rollback或結束會話時,

會清除臨時表資料。

on commit preserve rows -- 會話級別臨時表(退出登入會結束會話)

on commit delete rows -- 事務級別臨時表(提交或回滾會結束事務)

臨時表優缺點:

1. 在僅僅查詢資料時建議使用遊標。

2. 臨時表不會建立索引,所以如果資料量比較大或進行多次查詢時,不推薦使用。