我有一个名为tblProducts的表,包含3列:intID,dateMain,intStatus。
我有一个类似的存储过程:
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,那么显示status = 1的行和其他状态的行相同?
编辑:
如果includeStatus2 = 1(true),则检索status = 2的所有行。
如果includeStatus3 = 1(true),则退出所有status = 3的行
如果includeStatus2 = 0(false)则不检索status = 2
的行等
提前致谢。
答案 0 :(得分:4)
试试这个:
AND product.status1 = COALESCE(NULLIF(@includeStatus1, 0), product.status1)
如果@ includeStatus1为null或0,则实际上将忽略它。如果它是1,那么它将过滤结果。
答案 1 :(得分:0)
假设0不是有效状态,将此代码添加到WHERE子句应该有效。如果0是有效状态,则为SELECT参数传递NULL而不是0,或者在SELECT之前将0转换为NULL,这仍然有效。
and intStatus in (@includeStatus1*1, @includeStatus2*2, @includeStatus3*3, @includeStatus4*4)