tsql:是否有可能在select中嵌套case语句?
问题描述:
如何在SQL查询的select子句中嵌入if语句? 我知道使用大小写的情况下,然后X else y结束,但是如何以同样的方式对记录集中的每条记录执行嵌套。tsql:是否有可能在select中嵌套case语句?
if x.boy is not null then
x.boy
else if x.girl is not null
then x.girl
else if x.dog is not null
then x.dog
else
x.cat
这里是我的尝试:
SELECT top 10
id,
case when x.boy <> NULL then
x.boy
else case when x.girl <> NULL
x.girl
else case when x.dog <> NULL
x.dog
else x.cat
end as Who
from house x
这是正确的?
答
是的。案件中的案件没有任何问题。
虽然,这里是你的脚本,corectly写着:
SELECT top 10
id,
case
when x.boy IS NOT NULL then x.boy
else case
when x.girl IS NOT NULL THEN x.girl
else case
when x.dog IS NOT NULL THEN x.dog
else x.cat
end
end
end as Who
from house x
OR
SELECT top 10
id,
case
when x.boy IS NOT NULL then x.boy
when x.girl IS NOT NULL THEN x.girl
when x.dog IS NOT NULL THEN x.dog
else x.cat
end as Who
from house x
OR
SELECT top 10
id,
coalesce(x.boy, x.girl, x.dog, x.cat) AS Who
from house x
答
尝试了这一点:
SELECT top 10
id,
case when x.boy Is Not NULL then x.boy
else
case when x.girl Is Not NULL then x.girl
else
case when x.dog Is Not Null Then x.dog
else x.cat End
End
end as Who
from house x
虽然你可以只使用3210乔建议。
我得到一个错误与'as'结局作为谁..任何想法为什么? – phill 2010-10-14 20:32:18
错误是关键字'as'附近的语法不正确。 – phill 2010-10-14 20:32:58
我的答案有几种不同的方式来编写你的陈述是正确的。看到这些并添加您的评论 – 2010-10-14 20:35:02