T-SQL - How to write a conditional join

后端 未结 9 1882
轻奢々
轻奢々 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:28

    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.

提交回复
热议问题