Sql-Server

如何在不使用靜態組 ID 的情況下動態執行 join 語句?

  • June 1, 2021

我在 SQL Server 2014 上工作我需要在下面動態執行此語句

使用組 ID 靜態

因為我不知道使用的最大組 ID 可能是 10、15、20

那麼如何在不寫入靜態組 ID 的情況下動態執行下面的查詢呢?

  select r1.familyid, r1.companyid, r1.GlobalPnId,
    concat(
        r1.PortionKey,
        r2.PortionKey,
        r3.PortionKey,
        r4.PortionKey,
        r5.PortionKey,
        r6.PortionKey,
        r7.PortionKey,
        r8.PortionKey,
        r9.PortionKey
        ) as PartNumber
from GetFinalResult r1
left join GetFinalResult r2 on r2.familyid = r1.familyid and r2.GroupID = 2
left join GetFinalResult r3 on r3.familyid = r1.familyid and r3.GroupID = 3
left join GetFinalResult r4 on r4.familyid = r1.familyid and r4.GroupID = 4
left join GetFinalResult r5 on r5.familyid = r1.familyid and r5.GroupID = 5
left join GetFinalResult r6 on r6.familyid = r1.familyid and r6.GroupID = 6
left join GetFinalResult r7 on r7.familyid = r1.familyid and r7.GroupID = 7
left join GetFinalResult r8 on r8.familyid = r1.familyid and r8.GroupID = 8
left join GetFinalResult r9 on r9.familyid = r1.familyid and r9.GroupID = 9
where r1.GroupID = 1

SQL 小提琴我會處理它 https://dbfiddle.uk/?rdbms=sqlserver_2014&fiddle=d3156fd25c6fc6e673eaf299bf0a68c8

我首先將 cte 選擇到臨時表中並相應地對其進行索引,然後替換對臨時表的所有 cte 呼叫

您多次呼叫 cte,這非常複雜”,並且每次都必須對其進行評估….

引用自:https://dba.stackexchange.com/questions/292579