如何将查询结果插入全局临时表?

时间:2018-02-28 10:09:37

标签: sql oracle oracle11g temp-tables

create global temporary table temptbl (id )

 as

  WITH t1(id, REFERENCE_ORDER_ID) AS (

  SELECT id,
         REFERENCE_ORDER_ID
  FROM   CALL_MASTER
  WHERE  REFERENCE_ORDER_ID = '1761' or id = '1761'   -- 1654 1760
  UNION ALL

  SELECT t2.id,
         t2.REFERENCE_ORDER_ID
  FROM   CALL_MASTER t2, t1
  WHERE   t2.id = t1.REFERENCE_ORDER_ID 
  ), tt(id, REFERENCE_ORDER_ID) AS (

  SELECT id,
         REFERENCE_ORDER_ID
  FROM   CALL_MASTER
  WHERE  REFERENCE_ORDER_ID = '1761' or id = '1761'   -- 1654 1760
  UNION ALL

  SELECT t2.id,
         t2.REFERENCE_ORDER_ID
  FROM   CALL_MASTER t2, tt
  WHERE   t2.REFERENCE_ORDER_ID = tt.id
  )
  --insert into temptbl values  

  insert into temptable   select * from  
 --select into temptable  select * from   
(
select distinct id  FROM   t1;
union
select distinct id  FROM   tt; 
);
--insert  into temptable  values(id); 


select * from temptbl;

1 个答案:

答案 0 :(得分:1)

虽然您可以使用create-table-as-select(CTAS)语法创建全局临时表,但将with子句放在正确的位置:

create global temporary table temptbl (id) as
with t1(id, reference_order_id) as (
  select id,
         reference_order_id
  from   call_master
  where  reference_order_id = '1761' or id = '1761'   -- 1654 1760
  union all
  select t2.id,
         t2.reference_order_id
  from   call_master t2, t1
  where  t2.id = t1.reference_order_id 
),
tt(id, reference_order_id) as (
  select id,
         reference_order_id
  from   call_master
  where  reference_order_id = '1761' or id = '1761'   -- 1654 1760
  union all

  select t2.id,
         t2.reference_order_id
  from   call_master t2, tt
  where  t2.reference_order_id = tt.id
)
select * from  
(
  select distinct id from t1
  union
  select distinct id from tt
);

创建一次GTT会更常见:

create global temporary table temptbl (id number);

然后插入会话的相关记录:

insert into temptbl  
with t1(id, reference_order_id) as (
  select id,
         reference_order_id
  from   call_master
  where  reference_order_id = '1761' or id = '1761'   -- 1654 1760
  union all
  select t2.id,
         t2.reference_order_id
  from   call_master t2, t1
  where   t2.id = t1.reference_order_id 
),
tt(id, reference_order_id) as (
  select id,
         reference_order_id
  from   call_master
  where  reference_order_id = '1761' or id = '1761'   -- 1654 1760
  union all

  select t2.id,
         t2.reference_order_id
  from   call_master t2, tt
  where   t2.reference_order_id = tt.id
)
select * from  
(
  select distinct id  from   t1
  union
  select distinct id  from   tt
);

Global temporary tables是永久架构对象;只有他们持有的数据是临时的 - 对于将其插入表中的会话是私有的。在运行时创建GTT表明您可能做错了,并且需要创建一个GTT作为一次性并为每个使用它的会话填充它,或者可能应该使用完全不同的机制,如PL / SQL集合。

或者您可能来自另一个RDBMS,这种模式(使用GTT或私有临时表,在Oracle中不存在,直到版本18c)是必要的,但是您需要做一些实际上并不需要GTT或Oracle集合的东西。

顺便说一下,union(没有all)会删除重复项,因此您正在合并的两个查询中的distinct子句是多余的。