I have a table with several fields in it. I am trying to create a search filter in asp.net so that the user can search by one or a combination of fields. So basically I want to create a single stored procedure that takes 4 parameters and adds the parameter to the WHERE clause if its value is not equal ...
TableExample has 4 columns, Col1 Col2 Col3 Col4
I hope there is a way to do this with a single stored procedure, rather than creating it for every possible combination.
I tried something like this, which is wrong, but its what ive got so far.
THANKS!
CREATE PROCEDURE [dbo].[Search]
@Col1 int,
@Col2 int,
@Col3 int,
@Col4 int
AS
SET TRANSACTION ISOLATION LEVEL READ COMMITTED
SELECT *
FROM
[dbo].[TestTable]
WHERE
1=1
CASE
WHEN @Col1 IN NOT NULL
THEN AND [Col1] = @Col1
WHEN @Col2 IN NOT NULL
THEN AND [Col2] = @Col2
WHEN @Col3 IN NOT NULL
THEN AND [Col3] = @Col3
WHEN @Col4 IN NOT NULL
THEN AND [Col4] = @Col4
END
source
share