条件 where 子句 SQL Server 2012

Conditional where clause SQL Server 2012

我四处搜索,但没有找到与我要实现的目标类似的情况。我只想在条件为真时才执行where子句表达式,否则我想忽略不匹配的数据

Where (
        case when LeaveDateTime > FromDate and EnteringDateTime < ToDate then
        (dateadd(d, Threshhold, LeaveDateTime) >= EnteringDateTime
        end
);

我在“>=”附近收到语法错误 有人可以帮我解决这个问题吗?

用简单的逻辑替换:

Where (not (LeaveDateTime > FromDate and EnteringDateTime < ToDate) or
       dateadd(day, Threshhold, LeaveDateTime) >= EnteringDateTime
      );

如果变量取NULL值,那么逻辑就比较繁琐了。

您的版本不起作用,因为 case 是一个 标量表达式 。布尔比较 不是 标量表达式,因此它不能是 then.

返回的值

如果我尝试使用您的示例在 where 子句中使用条件来过滤我们的 table,您可能必须将其更改为类似;

WHERE 1 = (CASE
    WHEN when LeaveDateTime > FromDate and EnteringDateTime < ToDate
       THEN 1
    ELSE 0 END)

如果我没有正确理解你的问题:)

"execute where clause expression only when the condition is true, otherwise I want to ignore the data that doesn't match it"

既然你说你想忽略,即不包括数据,否则如果不满足第一个条件,那么听起来你想要一个简单的 AND。这可能不是您想要表达的意思,这就是为什么提供示例结果来澄清通常很重要。

Where 
( 
   (LeaveDateTime > FromDate and EnteringDateTime < ToDate) 
      AND
   dateadd(day, Threshhold, LeaveDateTime) >= EnteringDateTime
);