简体   繁体   中英

Nested CASE Statement With ELSe (SQL Server)

I have a CASE statement something like following

CASE 
       WHEN A IS NULL 
       THEN CASE
                 WHEN B IN ('C','D') THEN NULL
                 WHEN X NOT IN ('C','D') THEN Z
                 End
                 ELSE SOMETHING_ELSE -- Want to get here When 'A' IS NOT NULL
                 END AS 'Result'

I want to get to ELSE part when First CASE is not true ie 'A' is not NULL. Can anyone suggest if i have wrongly nested them? not getting results right.

Many Thanks,

First, you don't need to nest case statements. Just use one case:

select (CASE WHEN A IS NULL AND B IN ('C', 'D') THEN NULL
             WHEN A IS NULL AND X NOT IN ('C','D') THEN Z
             WHEN A IS NOT NULL THEN SOMETHING_ELSE
        END) as Result

Note that when A IS NULL but the first two conditions are not met, then the return value will be NULL .

Because case statements are evaluated sequentially, this is simpler to write as:

select (CASE WHEN A IS NOT NULL THEN SOMETHING_ELSE
             WHEN B IN ('C', 'D') THEN NULL
             WHEN X NOT IN ('C', 'D') THEN Z
        END) as Result

The first condition captures when A is not NULL . Hence the second two are when A is NULL .

You can add the second When to your case where you can check for the second condition and set value otherwise set default value.

CASE 
    WHEN A IS NULL THEN CASE
                          WHEN B IN ('C','D') THEN NULL
                          WHEN X NOT IN ('C','D') THEN Z
                        End
    WHEN A IS NOT NULL THEN yourdesiredvalue
    ELSE default value
    END AS 'Result'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM