T-SQL - How to write a conditional join

后端 未结 9 1865
轻奢々
轻奢々 2021-01-30 13:07

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

9条回答
  •  清酒与你
    2021-01-30 13:44

    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?

    • If filter parameter @ConditionId is null, then there's no child for outer join, and result will have all Parent's.
    • If filter parameter @ConditionId is not null, then outer join will join Child's with this parent, and condition (@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.

提交回复
热议问题