I want to create a stored procedure. If the parameter is -1 then there should not be a where clause on that column else there should be a WHERE clause. What's the best way to do it without a lot of IF branching?
I checked the archive. There are a few similar questions but not exactly the same.
CREATE PROCEDURE report
(
@site int,
@promo int,
@type int
)
AS
SET NOCOUNT ON
-- I want to avoid this:
IF @site = -1 AND @promo = -1 and @type = -1
BEGIN
SELECT * from table
END
IF @site > -1 AND @promo = -1 and @type = -1
BEGIN
SELECT * from table WHERE site = @site;
END
... -- other cases
ELSE -- all parameters are > -1
BEGIN
SELECT * from table
WHERE site = @site AND promo = @promo AND type = @type
END