I have a stored procedure with a number of parameters. I would like to write my query so that it joins with certain tables but only if a particular parameter has a value. Take
This is how I had done for my case.
DECLARE
@ColorParam varchar(500)
SET
@ColorParam = 'red, green, blue'
declare @Colors table
(
Color NVARCHAR(50) PRIMARY KEY
)
-- populate @Colors table by parsing the input param,
-- table can be empty if there is nothing to parse, i.e.: no condition
INSERT @Colors SELECT Value FROM dbo.Splitter(@ColorParam, ',')
SELECT
m.Col1,
c.Color
FROM
MainTable AS m
FULL JOIN -- instead of using CROSS JOIN which won't work if @Colors is empty
@Colors AS c
ON
1 = 1 -- the trick
WHERE
(@ColorParam IS NULL OR c.Color = m.Color)