[英]best way to select data from one table or another
I have two temporary tables, say #t1
and #t2
in Sql Server 2008. I need to create #t3
such as: 我有两个临时表,比如Sql Server 2008中的#t1
和#t2
。我需要创建#t3
例如:
#t1
has rows, indifferently of #t2
's contents, #t3
= select * from #t1
当#t1
有行时,与#t2
的内容无关, #t3
= select * from #t1
#t1
has no rows, #t3
= select * from #t2
当#t1
没有行时, #t3
= select * from #t2
we can assume #t1
and #t2
have the same columns but I don't think I would like to rely on that fact. 我们可以假设#t1
和#t2
具有相同的列,但我认为我不想依赖这个事实。
I was thinking of something that draws some logic out of ' if exists (select * ...)
' statements, but wouldn't there be better like some sort of bool operators ? 我正在考虑从' if exists (select * ...)
'语句中得出一些逻辑,但不会像某种bool运算符那样更好吗?
The simplest way is to implement the logic as: 最简单的方法是将逻辑实现为:
if (exists (select * from #t1))
begin
select *
into #t3
from #t1;
end;
else
begin
select *
into #t3
from #t2;
end;
You can do this in one statement as: 您可以在一个声明中执行此操作:
select t.*
into #t3
from ((select *
from #t1
)
union all
(select *
from #t2
where not exists(select * from #t1)
)
) t
However, I think the explicit if
is a clearer way to express your intent. 但是,我认为明确的if
是一种更清晰的方式来表达你的意图。
This query would do just that, would see if there are rows in t1
and in that case populate table t3
with the contents of t1
, provided they have the same columns, otherwise it populates t3
with the contents of t2
. 这个查询就是这样,会看到t1
是否有行,并且在这种情况下用t1
的内容填充表t3
,前提是它们具有相同的列,否则它用t2
的内容填充t3
。
IF(select count(*) from t1) > 0
BEGIN
select * into t3 from t1
END
ELSE
BEGIN
select * into t3 from t2
END
Here is a SQLFiddle so you can see how it works. 这是一个SQLFiddle,所以你可以看到它是如何工作的。 To test the case when t1
does not have any rows, just remove the line that inserts into t1
, rebuild schema and re-run the query. 要测试t1
没有任何行的情况,只需删除插入t1
的行,重建模式并重新运行查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.