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
You should be able to expand on this...
DECLARE @SQL varchar(max)
SET @SQL = 'SELECT * FROM PERSON P'
IF NULLIF(@ADDRESSID,"") IS NULL SET @SQL = @SQL + " INNER JOIN ADDRESSES A ON P.AddressID = A.AddressID"
EXEC sp_executesql @SQL, N'@ADDRESSID int', @ADDRESSID
What Quntin posted is nice however there are some performance issues with it. Believe it or not what is faster is to check each parameter and write the SQL Join based on the case
In addition:
IF @AddressParameter IS NOT NULL
BEGIN
SELECT blah1, blah2 FROM OneTable INNER JOIN AddressTable WHERE ....
-more code
END
ELSE...
BEGIN
END
...
Another thing you can do is perform the joins and in the query filter (the where clause) you can do:
WHERE
(Address = @Address OR @Address IS NULL)
Performance here is shady as well.
Left join and where clause should do the trick:
SELECT Customers.CustomerName, Customers.Country, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID
WHERE Country= @MyOptionalCountryArg or @MyOptionalCountryArg is null;
If I understand correctly it sounds like your join conditions would be the equivalent of
ON ((@AddressID IS NOT NULL) AND (alias.column = @AddressID))
and likewise for the group join.
I use this conditional join at times.
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)
Join the three tables together and use something like this in your WHERE clause:
WHERE Addresses.ID = COALESCE(@AddressID, Addresses.ID)
AND Groups.ID = COALESCE(@GroupID, Groups.ID)