T-SQL:在SELECT语句中是否可以使用嵌套的CASE语句?

17

如何在 SQL 查询的 SELECT 子句中嵌入一个嵌套的 IF 语句?我知道可以使用 case when condition then X else y end,但是如何以同样的方式为记录集中的每个记录执行嵌套的 IF 语句。

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

这个是否正确?

3个回答

24

是的。一个案例内嵌在另一个案例中并没有错误。

虽然,这是你的脚本,已经正确地编写:

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

或者

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

或者

SELECT top 10
    id,
    coalesce(x.boy, x.girl, x.dog, x.cat) AS Who
from house x

我的答案有几种不同的方式可以正确地编写您的语句。请查看它们并添加您的评论。 - Gabriel McAdams

17

你可以使用COALESCE来简化这个过程。

SELECT TOP 10 id, COALESCE(x.boy, x.girl, x.dog, x.cat) as Who
    FROM house x

0
尝试一下这个:

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

虽然你可以像Joe建议的那样使用coalesce


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接