繁体   English   中英

SQL查询有条件地使用不同的表

[英]SQL query to use different tables conditionally

我有一个存储过程,该存储过程根据输入参数使用不同的表进行联接。 目前,我必须编写两次SQL查询(仅表名称有所不同)。 是否可以将它们组合在一起,所以我不必重复两次SQL查询逻辑?

当前代码:

CREATE PROCEDURE SampleProc
    @Condition BIT
AS
    IF @Condition = 0 
    BEGIN
        SELECT * 
        FROM TableA1 A /* Use TableA1 instead of TableA2 */ 
        INNER JOIN TableB B ON A.Id = B.Id /* The rest of the query remains the same */ 
        /* Inner Join some more complex join logic */
    END
    ELSE 
    BEGIN
        SELECT * 
        FROM TableA2 A /* Use TableA2 instead of TableA1 */ 
        INNER JOIN TableB B ON A.Id = B.Id  /* The rest of the query remains the same */ 
        /* Inner Join some more complex join logic */
    END
END

一种可能的方法是先将TableA1 / TableA2数据存储到临时表,然后使用该临时表在复杂查询中进行联接。 有什么更好的办法吗?

如果两个表具有相同的结构(如临时表注释所隐含),则可以执行以下操作:

select . . .
from ((select a.* from tablea1 a where @condition = 0
      ) union all
      (select a.* from tablea2 a where @condition <> 0
      )
     ) a inner join
     b

另一个选择是动态SQL,但是维护起来很棘手-因为代码看起来像字符串。

有时,您也可以使用left join来执行此操作:

select b.*, coalesce(a1.col, a2.col) as col
from b left join
     tablea1 a1
     on a1.id = b.id and @condition = 0 left join
     tablea2 a2
     on a2.id = b.id and @condition <> 0
where a1.id is not null or a2.id is not null
         . . . 

尽管这应该具有良好的性能,但它的缺点是,对列的所有引用都需要使用coalesce()

如果TableA1和TableA2具有相同的列,请尝试此操作

        SELECT 
            * 
        From 
            (   select
                    *
                from
                    TableA1
                where
                    @Condition = 0
                union all
                select
                    *
                from
                    TableA2
                where
                    @Condition != 0) as A
        INNER JOIN 
            TableB B
        On 
            A.Id =B.Id

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM