Conditional JOIN Statement SQL Server

前端 未结 3 561
灰色年华
灰色年华 2020-12-05 05:57

Is it possible to do the following:

IF [a] = 1234 THEN JOIN ON TableA 
ELSE JOIN ON TableB

If so, what is the correct syntax?

3条回答
  •  遥遥无期
    2020-12-05 06:45

    I disagree with the solution suggesting 2 left joins. I think a table-valued function is more appropriate so you don't have all the coalescing and additional joins for each condition you would have.

    CREATE FUNCTION f_GetData (
        @Logic VARCHAR(50)
    ) RETURNS @Results TABLE (
        Content VARCHAR(100)
    ) AS
    BEGIN
        IF @Logic = '1234'
            INSERT @Results
                SELECT Content
                FROM Table_1
        ELSE
            INSERT @Results
                SELECT Content
                FROM Table_2
        RETURN
    END
    GO
    
    SELECT *
    FROM InputTable
        CROSS APPLY f_GetData(InputTable.Logic) T
    

提交回复
热议问题