簡體   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