T-SQL - How to write a conditional join

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

    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
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2021-01-30 13:28

    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;
    
    0 讨论(0)
  • 2021-01-30 13:32

    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.

    0 讨论(0)
  • 2021-01-30 13:37

    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)
        
    0 讨论(0)
  • 2021-01-30 13:40

    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)
    
    0 讨论(0)
提交回复
热议问题