2010-07-02 45 views
3

我有一個名爲tblProducts的表,有3列:intID,dateMain,intStatus。sql簡單的sproc - 過濾器

我有一個存儲過程,如下所示:

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 

我想知道的是,我怎麼可能會增加這包括基於BIT參數行。因此,如果includeStatus1 = 1,那麼顯示狀態爲1的行和其他狀態相同的行?

編輯:

如果includeStatus2 = 1(真),然後檢索所有行,其中狀態= 2

如果includeStatus3 = 1(真),那麼retireve所有行狀態= 3

如果includeStatus2 = 0(假),那麼不檢索行,其中狀態= 2

預先感謝。

+1

如果參數傳遞爲0,它應該只包含那些匹配0的參數,或者您是否想在這種情況下包含所有參數? – 2010-07-02 15:39:12

+0

如果BIT爲真,那麼我希望狀態= 1的行不要被檢索。將更新問題 – 2010-07-02 15:42:25

回答

4

試試這個:

AND product.status1 = COALESCE(NULLIF(@includeStatus1, 0), product.status1) 

如果@ includeStatus1爲空或0,這將有效地忽略。如果它是1,那麼它將過濾結果。

+0

+1。但是如果'status1'允許空值需要更多的代碼。 – a1ex07 2010-07-02 15:57:45

0

假設0不是有效狀態,將此代碼添加到您的WHERE子句應該工作。如果0是一個有效的狀態,那麼要麼爲NULL傳遞參數而不是0,要麼在0之前將0轉換爲NULL,這仍然可以工作。

and intStatus in (@includeStatus1*1, @includeStatus2*2, @includeStatus3*3, @includeStatus4*4)