我有一張表,它通過將兩個「節點」鏈接在一起來創建路徑。遞歸CTE返回路徑中的所有連接節點
Node
-----------
Id - Primary Key
Name
etc...
Path
------
Id - Primary Key
From - FK to Node
To - FK to Node
所以這個路徑:
W --- X --- Y --- Z
可以建這樣的:
Node
Id Name
--- -----
1 W
2 X
3 Y
4 Z
5 A
6 B
7 C
Path
Id From To
--- ------- -------
1 1 2
2 2 3
3 3 4
4 6 7
我想出了給定任何節點ID遞歸CTE查詢,遍歷的路徑和返回所有涉及的「路徑」。
declare @nodeId = 2
;WITH cte AS (
-- ANCHOR
-- Find one path involving Node
SELECT top 1 p.*, 0 as [Seq] FROM dbo.Path p WHERE [From] = @nodeId or [To] = @nodeId
union all
-- go left
select leftPath.*, cte.[Seq] - 1 as [Seq]
from [Path] leftPath
join cte on cte.[From] = leftPath.[To] and cte.[Seq] <= 0
union all
-- go right
select rightPath.*, cte.[Seq] + 1 as [Seq]
from [Path] rightPath
join cte on cte.[To] = rightPath.[From] and cte.[Seq] >= 0
)
SELECT cte.Id, cte.Seq, cte.From, cte.To
FROM cte
order by [Seq]
因此,這將返回所有路徑 -
Path
Id Seq From To
--- --- ------- -------
1 -1 1 2
2 0 2 3
3 1 3 4
但我怎麼能寫出給定的節點ID之一的查詢,穿越的路徑,左,右,並返回所有不同(有序)涉及的節點?
Id Name
--- -----
1 W
2 X
3 Y
4 Z
您的查詢似乎沒有工作,例如'description'不存在。請解決這個問題,我會看看http://rextester.com/DEVHNG47817 –
固定;請參閱:http://rextester.com/live/QBDQ1655 – user210757
該查詢不匹配您的輸出。不否定'Seq' –