問題描述
提前道歉,因為我覺得我可能忘記/遺漏了一些明顯的東西.開始;我在我的 WHERE 子句中使用 case 語句,以下工作正常:
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
我的問題"是我想在我的 ELSE 塊中添加一個額外的 OR 子句......像這樣:
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
當然,這會引發此錯誤:關鍵字OR"附近的語法不正確.在 ELSE 語句中
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
推薦答案
CASE
是一個返回一個值的表達式.您可以在兩個表達式之間執行 OR,而不是針對單個 CASE
表達式進行測試,唯一的區別是 else 子句.(使用 IN
作為編寫 SomeOtherCol = ... OR SomeOtherCol =
的快捷方式)你可以這樣做:
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)
我的猜測是這比您需要的邏輯更多,如果知道您的具體情況,可以編寫更簡單、更清晰的 else 語句.
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.
這篇關于帶 OR 的 where 子句中的 Case 語句的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!