Oracle中的臨時(shí)表用法匯總
2024-08-29 13:29:52
供稿:網(wǎng)友
 
說(shuō)明:下文中的一些說(shuō)明和示例代碼摘自csdn,恕不一一指明出處,在此一并對(duì)相關(guān)作者表示感謝! 如果作者有異議,請(qǐng)來(lái)信說(shuō)明
 
1 語(yǔ)法 在oracle中,可以創(chuàng)建以下兩種臨時(shí)表: 
1) 會(huì)話特有的臨時(shí)表 
create global temporary <table_name> (<column specification> ) 
on commit preserve rows; 
2) 事務(wù)特有的臨時(shí)表 
create global temporary <table_name> (<column specification> ) 
on commit delete rows; 
create global temporary table mytemptable 
所建的臨時(shí)表雖然是存在的,但是如果insert 一條記錄然后用別的連接登上去select,記錄是空的。
--on commit delete rows 說(shuō)明臨時(shí)表是事務(wù)指定,每次提交后oracle將截?cái)啾恚▌h除全部行) 
--on commit preserve rows 說(shuō)明臨時(shí)表是會(huì)話指定,當(dāng)中斷會(huì)話時(shí)oracle將截?cái)啾怼?br>
2 動(dòng)態(tài)創(chuàng)建 
create or replace procedure pro_temp(v_col1 varchar2,v_col2 varchar2) as
v_num number;
begin
select count(*) into v_num from user_tables where table_name='t_temp';
--create temporary table
if v_num<1 then
execute immediate 'create global temporary table t_temp (
col1 varchar2(10),
col2 varchar2(10)
) on commit delete rows';
end if;
--insert data
execute immediate 'insert into t_temp values('''||v_col1||''','''||v_col2||''')';
execute immediate 'select col1 from t_temp' into v_num;
dbms_output.put_line(v_num);
execute immediate 'delete from t_temp';
commit;
execute immediate 'drop table t_temp';
end pro_temp;
測(cè)試:
15:23:54 sql> set serveroutput on
15:24:01 sql> exec pro_temp('11','22');
11
pl/sql 過(guò)程已成功完成。
已用時(shí)間: 00: 00: 00.79
15:24:08 sql> desc t_temp;
error:
ora-04043: 對(duì)象 t_temp 不存在
 
3 特性和性能(與普通表和視圖的比較) 臨時(shí)表只在當(dāng)前連接內(nèi)有效臨時(shí)表不建立索引,所以如果數(shù)據(jù)量比較大或進(jìn)行多次查詢時(shí),不推薦使用數(shù)據(jù)處理比較復(fù)雜的時(shí)候時(shí)表快,反之視圖快點(diǎn)在僅僅查詢數(shù)據(jù)的時(shí)候建議用游標(biāo): open cursor for 'sql clause';
歡迎補(bǔ)充!