2011-03-24 100 views
1

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 

我试了一下,它返回第一个部分。

+0

你应该得到一个错误。 – 2011-03-24 12:42:21

+0

您是否尝试过UNION? – malinois 2011-03-24 12:43:33

回答

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 
+0

非常感谢,我从来没有听说过工会之前,听起来要走的路,没有真正需要临时表 – Charbel 2011-03-24 13:00:02

+0

@Charbel - 啊如果临时表的目的只是巩固结果,那么肯定你应该使用'联盟所有直接。 – 2011-03-24 13:04:26

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