2010-07-05 69 views
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 

我知道这可能似乎是一个愚蠢的问题,但如果@startDate和@EndDate都是null,则我希望它在where子句中返回忽略日期检查的行。

任何帮助将不胜感激。

回答

6

这应该做

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

ISNULL产生了第二个值,如果第一个值是零。

因此:

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

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

+0

+1。相同我的(删除)答案只有更好:) – 2010-07-05 11:26:24

+0

谢谢,完美的作品 – 2010-07-05 11:43:54

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,但由于这是一个存储过程:

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

这是很多重复,但是,有一些简单的解决方案(Lieven,IordanTanev和我都得到相同的解决方案) – 2010-07-05 11:27:14

0

我会用克里斯克劳斯的解决方案,但改变“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