Simple sql sproc filter

I have a table called tblProducts with three columns: intID, dateMain, intStatus.

I have a stored procedure like:

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

I would like to know how I can add to this to include strings based on BIT parameters. So, if includeStatus1 = 1, then display the lines where status = 1 and the same for other statuses?

EDIT:

if includeStatus2 = 1 (true) then retrieve all rows where status = 2.

if includeStatus3 = 1 (true) then retireve all rows where status = 3

if includeStatus2 = 0 (false), then do not fetch lines where status = 2

etc.

Thanks in advance.

+3
source share
2 answers

Try the following:

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

@includeStatus1 null 0, . 1, .

+4

, 0 , WHERE . 0 - , NULL 0, 0 NULL SELECT, .

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

Source: https://habr.com/ru/post/1752852/


All Articles