我需要在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
答案 0 :(得分:8)
为什么不使用OR
条件?
SELECT *
FROM myTable
WHEN id = 12345
AND ((TermDate IS NULL AND
getdate() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)) OR
GETDATE() < TermDate)
答案 1 :(得分:2)
由于我们都发布了三个确切的答案,显然太多了,这里是一个使用case when
构造的版本。
使用它:
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
答案 2 :(得分:2)
您可以使用ANDs
和ORs
来完成此操作。请尝试以下查询。
Select *
From myTable
where id = 12345
AND ((TermDate IS NULL
AND GETDATE() BETWEEN StartDate AND DATEADD(dd, 30, StartDate))
OR (GETDATE() < TermDate))