I am creating a stored procedure to do a search through a table. I have many different search columns, all of which are optional. Is there a way to create a stored procedure that will handle this? Let's say I have a table with four columns ID, N1, N2 and N3. I could do something like this:
Table:
INSERT INTO [dbo].[Sample]
VALUES ('1', 'A,B,C', 'A,B,C', 'A,B,C'),
('2', 'B,D,N', 'B,D,N', 'B,D,N'),
('3', 'A,N,S', 'A,N,S', 'A,N,S'),
('4', 'S,F,G', 'S,F,G', 'S,F,G'),
('5', 'D,F,K', 'D,F,K', 'D,F,K'),
('6', 'S,H,Y', 'S,H,Y', 'S,H,Y'),
('7', 'Z,B,C', 'Z,B,C', 'Z,B,C')
Stored procedure:
CREATE PROCEDURE dbo.Sample2
@n11 varchar(max) = null,
@n12 varchar(max) = null,
@n21 varchar(max) = null,
@n22 varchar(max) = null,
@n31 varchar(max) = null,
@n32 varchar(max) = null
AS
BEGIN
SELECT COUNT(*)
FROM Sample
WHERE
(@n11 IS NULL OR Sample.N1 LIKE '%' + @n11 + '%'
OR @n12 IS NULL OR Sample.N1 LIKE '%' + @n12 + '%')
AND (@n21 IS NULL OR Sample.N2 LIKE '%' + @n21 + '%'
OR @n22 IS NULL OR Sample.N2 LIKE '%' + @n22 + '%')
AND (@n31 IS NULL OR Sample.N3 LIKE '%' + @n31 + '%'
OR @n32 IS NULL OR Sample.N3 LIKE '%' + @n32 + '%')
END
If user enters @n11 as A and leave the rest, since N1 contains A in 2 rows, output should be 2 but above query is providing 7. If a parameter is not specified, I need that to be ignored and pass the rest to where condition.