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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-01 01:07:46  来源:igfitidea点击:

Add Case Statement in Where Clause

sqlselectswitch-statementcase

提问by CipherIS

I need to add a casestatement in a whereclause. I want it to run either statement below depending on the value of TermDate.

我需要casewhere子句中添加一个语句。我希望它根据 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 ORcondition?

为什么不直接使用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 whenconstruction.

由于我们都发布了三个确切的答案,显然太多了,这里有一个使用您的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 ANDsand 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))