SQL查询日期空值检查

4
我有以下存储过程。
ALTER PROCEDURE [dbo].[spList_Report] 
  @id INT, 
  @startDate DATETIME = NULL, 
  @endDate DATETIME = NULL, 
  @includeStatus1 BIT, 
  @includeStatus2 BIT, 
  @includeStatus3 BIT, 
  @includeStatus4 BIT 
 
AS 
  SET NOCOUNT ON 
 
  SELECT * 
  FROM 
    tblProducts as products 
  WHERE  
    product.intID = @id 
    AND product.dateMain >= @startDate  
    AND product.dateMain <= @endDate 

如果 @startDate@endDate 都为null,则希望查询结果忽略 where 子句中的日期检查。如何实现?
4个回答

9

这应该可以做到

AND product.dateMain >= ISNULL( @startDate, 0)
AND product.dateMain <= ISNULL( @endDate, product.dateMain + 1)

ISNULL函数用于在第一个值为null时返回第二个值。

因此:

如果@startDate为null,则dateMain必须大于0(1900-01-01)

如果@endDate为null,则dateMain必须小于dateMain + 1 day


2
你可以尝试像这样做:
ALTER PROCEDURE [dbo].[spList_Report] 
  @id INT, 
  @startDate DATETIME = NULL, 
  @endDate DATETIME = NULL, 
  @includeStatus1 BIT, 
  @includeStatus2 BIT, 
  @includeStatus3 BIT, 
  @includeStatus4 BIT 

AS 
  SET NOCOUNT ON 

  SELECT * 
  FROM 
    tblProducts as products 
  WHERE  
    product.intID = @id 
    AND product.dateMain >= ISNULL( @startDate, product.dateMain )  
    AND product.dateMain <= ISNULL( @endDate,  product.dateMain ) 

0

你可以在SQL中使用“or”,但由于这是一个存储过程:

If @startdate is null Or @enddate is null
   begin
      select without using a date range
   end
Else
   begin
      select using date range
   end

这是很多重复的内容,而且有更简单的解决方案(Lieven、IordanTanev和我都得出了相同的解决方案)。 - David Hedlund

0
我会使用Kris Krause的解决方案,但将“IF”语句更改为使用“AND”。我认为如果您使用前两个解决方案,查询引擎可能会在日期字段上执行表/索引扫描。为了获得最佳性能,您希望尽可能简洁地保持查询,因此不要在不必要的列上运行查询。
IF @startdate IS NULL AND @enddate IS NULL
BEGIN
    SELECT * FROM tblProducts as products WHERE  
    product.intID = @id 
END
ELSE
BEGIN
    SELECT * FROM tblProducts as products WHERE  
    product.intID = @id 
    AND product.dateMain >= @startDate  
    AND product.dateMain <= @endDate 
END

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接