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
Uh, probably all of you have resolved this so far.
As i understand You, you want to have 'dynamic' query, to join table if parameter exists, or to omit join if parameter is null. Secret is in using left outer join. Like:
SELECT p.*
FROM Parent AS p
LEFT OUTER JOIN Child AS c ON p.Id = c.ParentId
WHERE
(@ConditionId IS NULL OR c.ConditionId = @ConditionId)
How this works?
(@ConditionId IS NULL OR c.ConditionId = @ConditionId)
will throw out Parent's which didn't have joined Child's with condition c.ConditionId = @ConditionId
.LEFT OUTER JOIN for sure have performance issue, but as much as this works fast, i don't want to concatenate string's to create query.