if else ms sql 服务器中 where 子句中的条件

if else condition in where clause in ms sql server

我正在尝试根据以下 2 个条件从连接表中检索记录:

Where if(b.enddate is null)
         a.starttime >= b.starttime
      else
         a.starttime >= b.starttime and a.endtime <= b.endtime

我看过使用 case when 的例子,但结果不是我想要的。请帮助我将此条件转换为正确的 sql 格式。

您不需要使用 case 表达式,这可以在 WHERE 子句

中使用 OR 来完成
... Where 
( b.enddate is null and a.starttime >= b.starttime)
or     
( b.enddate is not null and a.starttime >= b.starttime and a.endtime <= b.endtime)

关于:

   WHERE (b.enddate is null AND a.starttime >= b.starttime) OR (b.enddate is not null AND a.starttime >= b.starttime and a.endtime <= b.endtime) 

先生,试试这个,

   where (b.enddate is null and a.starttime >= b.starttime) OR (a.starttime >= b.starttime and a.endtime <= b.endtime) 

谢谢:)

我认为我们可以简单地做到这一点因为在这两种情况下a.starttime >= b.starttime都是适用的所以我们只需要处理a.endtime <= b.endtime条件以防万一b.enddateNULL or NOT NULL 所以我做如下:

WHERE a.starttime >= b.starttime and (b.enddate is null OR a.endtime <= b.endtime)

为简单起见,您可以尝试以下示例条件逻辑:

DECLARE @enddate datetime2(7);
SET @enddate = NULL;

SELECT @enddate;

IF @enddate IS NULL
    SELECT 1, 2 FROM dbo.table_a as a
    INNER JOIN dbo.table_b as b ON a.id = b.id
    WHERE a.starttime >= b.starttime
ELSE
    SELECT 1, 2 FROM dbo.table_a as a
    INNER JOIN dbo.table_b as b ON a.id = b.id
    WHERE a.starttime >= b.starttime and a.endtime <= b.endtime

这为您提供了 2 个单独的执行计划的好处。因此,如果您决定优化您的 SQL 语句,它会更容易(例如索引、计划稳定性、移动到 sp 等)。