如何使用Oracle全局临时表?

5

我尝试使用Oracle全局临时表而不需要在数据库中物理创建一张表。以下代码无法正常工作,请问有人可以解释一下如何正确地使用全局临时表吗?

declare
  global temporary table my_temp_table(column1 number) on commit preserve rows;    
begin
  insert into my_temp_table (column1) values (1);
  select * from my_temp_table;   
end;

创建磁盘上的问题是什么? - RGO
2
全局临时表必须在数据库中创建,不能在PL/SQL中本地定义。在PL/SQL中有其他保存数据的方法,可以使用集合。适当的工具取决于您要做什么 - 首先为什么需要GTT?您放入其中的数据的最终目标是什么? - Alex Poole
@AlexPoole:链接有一个声明会话临时表的功能,请查看链接,我不确定如何使用它,但很愿意探索。 - Gaurav Soni
@GauravSoni - 这是Derby的文档,而不是Oracle RDBMS的文档? - Alex Poole
@AlexPoole:啊,非常抱歉,也许Matthew也因此感到困惑。 - Gaurav Soni
3个回答

4
除非您使用EXECUTE IMMEDIATE,否则无法在PL/SQL内创建表。请尝试以下操作:
create global temporary table my_temp_table(column1 number) on commit preserve rows;    

insert into my_temp_table (column1) values (1);
select * from my_temp_table;   

oracle-base.com文章参考在上面的评论1中,然后解释了它的用法,并举了一个例子,说明当会话在断开连接后再次连接时会发生什么。结果是其数据将被清除。 - Pankaj
使用它的主要好处将是减少生成的重做。撤销仍将与传统表格相同。 - Pankaj

4
使用execute immediate试一下以下代码:它使用异常处理程序来忽略如果表已经存在的情况;此外,请注意,您不能在PLSQL内部使用SQL select。
DECLARE
  l_column1 number;
begin
  begin
    execute immediate 'create global temporary table my_temp_table(column1 number) 
on commit   preserve rows';
  exception when others
    then
    dbms_output.put_line(sqlerrm);
  end;
  insert into my_temp_table (column1) values (1);
  select * into l_column1 from my_temp_table where column1=1;
  dbms_output.put_line('the temp value is '||l_column1);   
end;

4

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接