T-SQL Nested Case Statement - Else Continue Nesting Case

1.6k Views Asked by At

In SQL Server, is there a way for nested case statements to ELSE continue the nesting CASE statement?

CASE
WHEN ... then
          CASE
          WHEN  ... THEN
          ELSE **[Continue to below WHEN]** END
WHEN ... then
WHEN ... then
ELSE ... END

Wondering if I can keep the code clean by not copy/pasting the proceeding WHEN statements into the nested CASE.

1

There are 1 best solutions below

0
Joel Coehoorn On

Flatten the nesting. So instead of this:

CASE
WHEN A then
          CASE
          WHEN B THEN C
          WHEN D THEN E
          ELSE **[Continue to below WHEN]** END
WHEN F then G
WHEN H then I
ELSE J END

You have this:

CASE
WHEN A AND B THEN C
WHEN A AND D THEN E
WHEN F then G
WHEN H then I
ELSE J END

A CASE expression (not statement: CASE cannot branch among SQL segments, only return a value) will stop at the first match, so by flattening the nesting and using and AND to tie in the nested conditions you will get the desired behavior.