日期:2014-05-18  浏览次数:20516 次

一次查询,把结果放入两个临时表
一个表,
A B C三列

可以这样把查询结果放到两个临时表里

select * into #t1 from tb where C=1 and B is null
select * into #t2 from tb where C=1 and A is null

这样要查两次,当然也可以这样

select * into #t from tb where c=1;
select * into #t1 from #t where b is null
select * into #t2 from #t where a is null
这样的话多了一次into表,into占整个查询所占开销的比例也不小。

有没有什么好办法
像这样
select * 
(when case b is null then into #t1 else into #t2 end) from tb where c=1
但不知道上面这个我想出来的代码可行不可行

------解决方案--------------------
SQL code

declare @table table (a int,b int,c int)
insert into @table
select null,null,1 union all
select 1,null,1 union all
select null,1,1 union all
select 2,2,1

select * from @table
/*
a           b           c
----------- ----------- -----------
NULL        NULL        1   --插入#t1和#t2
1           NULL        1   --插入#t2
NULL        1           1   --插入#t1
2           2           1   --不满足条件不要
*/

--确认楼主是不是这个意思?

------解决方案--------------------
还是分开进行吧。
------解决方案--------------------
select * into #t1 from tb where C=1 and (B is null or A is null)
或者
select * into #t1 from
(
select * from tb where C=1 and B is null 
union
select * from tb where C=1 and A is null 
) as a