SQL 在 Where 子句中添加 Case 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21919089/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Case Statement in Where Clause
提问by CipherIS
I need to add a case
statement in a where
clause. I want it to run either statement below depending on the value of TermDate.
我需要case
在where
子句中添加一个语句。我希望它根据 TermDate 的值运行以下任一语句。
Select *
from myTable
where id = 12345
AND TermDate CASE
WHEN NULL THEN
AND getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)
ELSE
AND GETDATE < TermDate
END
回答by Mureinik
Why not just use an OR
condition?
为什么不直接使用OR
条件?
SELECT *
FROM myTable
WHEN id = 12345
AND ((TermDate IS NULL AND
getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)) OR
GETDATE() < TermDate)
回答by Patrick Hofman
Since we all posted three exact answers, obviously too much, here a version that uses your case when
construction.
由于我们都发布了三个确切的答案,显然太多了,这里有一个使用您的case when
构造的版本。
use this:
用这个:
select *
from myTable
where id = 12345
AND case
when TermDate IS NULL
AND getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)
then 1
when GETDATE < TermDate
then 1
else 0
end
= 1
回答by user2989408
You can accomplish this using ANDs
and ORs
. Try the following query.
您可以使用ANDs
和来完成此操作ORs
。尝试以下查询。
Select *
From myTable
where id = 12345
AND ((TermDate IS NULL
AND GETDATE() BETWEEN StartDate AND DATEADD(dd, 30, StartDate))
OR (GETDATE() < TermDate))