SQL查询日期null检查

Ria*_*ney 3 sql

我有以下存储过程.

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 
Run Code Online (Sandbox Code Playgroud)

我知道这可能看起来像一个愚蠢的问题,但如果@startDate AND @endDate都为null,那么我希望它返回行忽略where子句中的日期检查.

任何帮助将不胜感激.

Dav*_*und 7

这应该做

AND product.dateMain >= ISNULL( @startDate, 0)
AND product.dateMain <= ISNULL( @endDate, product.dateMain + 1)
Run Code Online (Sandbox Code Playgroud)

ISNULL 如果第一个值为null,则产生第二个值.

从而:

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

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