开发者

SQL Server 2000 how to form a case within a case statement?

Is it possible to have a case statement within a case's when true then statement?

case when true then 
   case when false then 'test0'
   else 'test1'
   end
else
    case when false then 'test2'
    else 'test3'
    end
end
开发者_Python百科

Note sure where to put the end statements?


Absolutely. The Case expression does not know it is embedded in another case expression. Each Case expression needs an End keyword:

Select Case
        When Foo = Bar Then 'Test0'
        Else Case
                When Gamma = Theta Then 'Test1'
                End
        End

Another way is to simply stack the expressions

Select Case
        When Foo = Bar Then 'Test0'
        When Gamma = Theta Then 'Test1'
        Else 'Blah'
        End

When stacked like this, the expressions are executed in the order they are written until one When expression evaluates to true (i.e., you get to one of the Then expressions).


Your code looks good as is. its ok to have the End End next to each other as the interpreter understands the embedding.


It may be good to use parenthesis or identation (or both) so it's obvious which case goes with which end.

case when true then 
  (  case when false then 'test0'
     else 'test1'
     end
  ) 
else
  ( case when false then 'test2'
    else 'test3'
    end
  )
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜