我有以下格式的 SQL Server 資料:

上表中,parentid和sourceid是相關的,就像父子關系。
在第一行的 parentid 'A' 是第二行的 sourceid。用戶將提供 sourceid 的輸入,并根據該 sourceid,我需要獲取其相關的子記錄。
例如,如果用戶提供輸入源 id 為“A1”,則輸出應如下所示:

我嘗試使用自聯接,但我無法在表中獲取相關的子記錄。
select *
from testrecords1 t1
join testrecords1 t2 on t1.parentid = t2.sourceid
where t1.sourceid = 'A1'
此查詢僅產生一條記錄。請提供更正/建議以實作所需的輸出。
uj5u.com熱心網友回復:
您可以將公共表運算式 (CTE)用于遞回查詢。
查詢可以寫成:
;with MyCTE
as
(
SELECT Parentid, Sourceid from testrecords1 where SourceId = @SourceId
UNION ALL
SELECT t1.Parentid, t1.Sourceid from testrecords1 t1
inner join MyCTE t2 on t1.SourceId = t2.Parentid
)
SELECT * FROM MyCTE
@SourceId過濾器的引數在哪里。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/365548.html
標籤:sql-server 加入 亲子 公用表表达式 自加入
