這...
Declare @data Table
(
Parent int,
Child int
)
insert into @data values
(190, 192),
(192, 180),
(180, 185),
(185, 184),
(190, 191),
(191, 197),
(197, 200)
Declare @Id as Int = 184
/*
CompleteData - query produce following output
ID ParentId
----------- -----------
180 192
184 185
185 180
190 NULL -- we discoverd this missing data
191 190
192 190
197 191
200 197
ChildHierarchyData - query produce following ouput
ID ParentID Level
----------- ----------- -----------
184 185 0
185 180 1
180 192 2
192 190 3
190 NULL 4
Concatinated - query conact all ID from above result
*/
;with CompleteData
as
(
Select Child ID, Parent ParentId from @data
UNION
Select Child.Parent Id, Parent.Parent ParentId From @data Child
Left Outer Join @data Parent
on Child.Parent = parent.Child
WHERE
parent.Parent IS NULL
),
ChildHierarchyData(ID,ParentID, Level)
as
(
Select ID,ParentID, 0 as Level from CompleteData Where ID = @Id
union all
Select CompleteData.ID, CompleteData.ParentID, ChildHierarchyData.Level +1 from CompleteData
INNER Join ChildHierarchyData
on ChildHierarchyData.ParentID = CompleteData.ID
),
Concatinated(result)
as
(
Select Cast((select Cast(ID as nvarchar) + ',' [data()] from ChildHierarchyData Order By Level Desc FOR XML Path('')) as Nvarchar(max))
)
select Left(result, len(result)-1) as Result from Concatinated
你試過這個嗎? http://stackoverflow.com/questions/9004543/recursive-child-parent-queries-in-t-sql – jcwrequests
我不認爲這可以在單個查詢中完成,因爲您正在有效地擴展遞歸關係。我認爲可以使用存儲函數完成(我不確定SQL Server是否支持存儲函數中的遞歸)。假設它被支持,您可以輕鬆地編寫一個調用存儲函數的簡單查詢。 – Zenilogix
它絕對可以在一個查詢(或兩個)中完成。如果這個問題在幾個小時內仍然開放,我會提供一個答案。 – Szymon