Case statement in where clause w/an OR

こ雲淡風輕ζ 提交于 2019-12-11 08:12:32

问题


Apologies in advance since I feel like I'm probably forgetting/missing something obvious on this one. Here goes; I'm using a case statement in my WHERE clause, the below works fine:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol =  
(
CASE WHEN (@Year = 0 AND @Period = 0) THEN
@SomeVal
     WHEN...
...
     ELSE
@SomeVal
END 

My "issue" is that I want to add an additional OR clause to my ELSE block..something like this:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol =  
(
CASE WHEN (@Year = 0 AND @Period = 0) THEN
@SomeVal
     WHEN...
...
     ELSE
@SomeVal OR @SomeVal - 1
END 

Naturally, this throws this error: Incorrect syntax near the keyword 'OR'. within the ELSE statement

Hence my question...what is the correct/alternate logic I can use to accomplish this?
Thank you in advance


回答1:


CASE is an expression that returns one value. Instead of testing against the single CASE expresssion, you could do an OR between two, that only difference is the else clause. (Using IN as a shortcut for writing SomeOtherCol = ... OR SomeOtherCol =) You could do:

WHERE r.[SomeCol] = @SomeColVal
AND SomeOtherCol in   
    (CASE WHEN (@Year = 0 AND @Period = 0) THEN
        @SomeVal
        CASE WHEN...
            ...
        CASE ELSE
        @SomeVal END,
    CASE WHEN (@Year = 0 AND @Period = 0) THEN
        @SomeVal
        CASE WHEN...
            ...
        CASE ELSE
        @SomeVal - 1 END)

My guess is this has more logic than you need, and if the specifics of your situation were known a much simpler and clearer else statement could be written.



来源:https://stackoverflow.com/questions/1257516/case-statement-in-where-clause-w-an-or

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!