首页 > 数据库 > Oracle > 正文

Oracle中的临时表用法汇总

2024-08-29 13:29:52
字体:
来源:转载
供稿:网友

说明:下文中的一些说明和示例代码摘自csdn,恕不一一指明出处,在此一并对相关作者表示感谢! 如果作者有异议,请来信说明

 
1 语法 在oracle中,可以创建以下两种临时表:
1) 会话特有的临时表
create global temporary <table_name> (<column specification> )
on commit preserve rows;
2) 事务特有的临时表
create global temporary <table_name> (<column specification> )
on commit delete rows;
create global temporary table mytemptable
所建的临时表虽然是存在的,但是如果insert 一条记录然后用别的连接登上去select,记录是空的。


--on commit delete rows 说明临时表是事务指定,每次提交后oracle将截断表(删除全部行)
--on commit preserve rows 说明临时表是会话指定,当中断会话时oracle将截断表。

2 动态创建 
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;

测试:

15:23:54 sql> set serveroutput on
15:24:01 sql> exec pro_temp('11','22');
11

pl/sql 过程已成功完成。

已用时间: 00: 00: 00.79
15:24:08 sql> desc t_temp;
error:
ora-04043: 对象 t_temp 不存在

 
3 特性和性能(与普通表和视图的比较) 临时表只在当前连接内有效临时表不建立索引,所以如果数据量比较大或进行多次查询时,不推荐使用数据处理比较复杂的时候时表快,反之视图快点在仅仅查询数据的时候建议用游标: open cursor for 'sql clause';

欢迎补充!

 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表