在Where子句中添加Case语句

时间:2014-02-20 20:41:15

标签: sql select switch-statement case

我需要在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

3 个答案:

答案 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)

您可以使用ANDsORs来完成此操作。请尝试以下查询。

Select * 
From myTable
where id = 12345
AND ((TermDate IS NULL 
          AND GETDATE() BETWEEN StartDate AND DATEADD(dd, 30, StartDate)) 
    OR (GETDATE() < TermDate))