2010-07-05 70 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