sql中的条件where子句用于日期范围

时间:2014-02-16 12:13:41

标签: sql-server tsql

我有一个存储过程,它有两个参数:

@PublishedFrom SMALLDATETIME = NULL,
@PublishedDeadline SMALLDATETIME = NULL

我希望当PublishedDeadline为null时,WHERE条件应为:

WHERE (dbo.Vacancies.StartDate >= @PublishedFrom 
       OR @PublishedFrom IS NULL)

但如果PublishedDeadline不为空,那么WHERE子句应该像

WHERE v.startdate <= @PublishedDeadline 
  and @PublishedFrom <= v.EndDate

如何在SQL中应用条件where子句?

请建议

2 个答案:

答案 0 :(得分:4)

以下内容对您有用:

WHERE (PublishedDeadline IS NULL 
       AND (
            dbo.Vacancies.StartDate >= @PublishedFrom 
            OR @PublishedFrom IS NULL
       ) OR (
        PublishedDeadline IS NOT NULL 
        AND v.startdate <= @PublishedDeadline 
        AND @PublishedFrom <= v.EndDate
       )

只需将IS NULL / IS NOT NULL条件与其他条件结合起来

答案 1 :(得分:0)

由于您使用的是存储过程,因此您可能希望获得更详细,更易读的查询

if (@PublishedDeadline is NULL)
BEGIN
   Select * from dbo.Vacancies
   WHERE (dbo.Vacancies.StartDate >= @PublishedFrom 
   OR @PublishedFrom IS NULL)
END
else
BEGIN
   Select * from dbo.Vacancies
   WHERE v.startdate <= @PublishedDeadline 
    and @PublishedFrom <= v.EndDate
END