T-SQL - How to write a conditional join

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

提交回复
热议问题