反复选择临时表

时间:2011-03-24 12:41:13

标签: sql select

HI,

如何重复选择同一临时表,然后返回完整结果。

类似

select 
   col1, 
   col2 
into #temp 
where 
   col4="abc" 
   and col5=10
select 
   col1, 
   col10 
into #temp 
where 
   col4="dbe" 
   and col5=15
select * from #temp

我试过了,它只返回了第一部分。

2 个答案:

答案 0 :(得分:4)

    /*First one creates the table*/ 
   select 
       col1, 
       col2 
    into #temp 
    from something  
    where 
       col4="abc" 
       and col5=10

/*Now insert into the table that you just created*/     
    insert into #temp 
    select 
       col1, 
       col10 
    from something  
    where 
       col4="dbe" 
       and col5=15
    select * from #temp

您也可以

select 
       col1, 
       col2 
    into #temp FROM (
   select 
       col1, 
       col2 
    from something       
    where 
       col4="abc" 
       and col5=10
union all
    select 
       col1, 
       col10 
    from something         
    where 
       col4="dbe" 
       and col5=15) derived

答案 1 :(得分:0)

以上代码最终会出错。 你应该在第一次选择之后插入。 试试这个:

 select 
       col1, 
       col2 
    into #temp 
    where 
       col4="abc" 
       and col5=10;
    insert into #temp 
    select 
       col1, 
       col10 
    where 
       col4="dbe" 
       and col5=15;

    select * from #temp