开发者

sql server 2005/2008 conditional join

Is there such thing like conditional join:

SELECT *
FROM TABLE1 A
    IF (a=='TABLE2') THEN INNER JOIN TABLE2 B ON A.i开发者_如何学运维tem_id=B.id
    ELSE IF (a=='TABLE3') THEN INNER JOIN TABLE3 C ON A.item_id=C.id

While a is a field in TABLE1.

I like to use this in stored procedures without using dynamic sql (without writing query as string and EXEC(@query)).

EDIT: I can't write:

IF (a=='TABLE2) THEN queryA
ELSE IF (a=='TABLE3') THEN queryB

Because a is a field of TABLE1.


EDIT: Modified answer based on comment below:

You could try to get clever with some left joins. This will return more columns, so you'd probably want to be more discriminating than just SELECT *.

SELECT *
    FROM TABLE1 A
        LEFT JOIN TABLE2 B
            ON A.item_id = B.id
                AND A.a = 'TABLE2'
        LEFT JOIN TABLE3 C
            ON A.item_id = C.id
                AND A.a = 'TABLE3'
    WHERE (B.id IS NOT NULL AND A.a = 'TABLE2')
       OR (C.id IS NOT NULL AND A.a = 'TABLE3')


Updated the query as requried:

SELECT * FROM
(
    SELECT * 
        FROM TABLE1 A  INNER JOIN TABLE2 B 
            ON A.a='TABLE2' --This will eleminate the table rows if the value of A.a is not 'TABLE2' 
         AND A.item_id=B.id) A,
             (SELECT * FROM
             INNER JOIN TABLE3 C 
            ON A.a='TABLE3' --This will eleminate the table rows if the value of A.a is not 'TABLE3'
            AND A.item_id=C.id 
                ) B
) a
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜