5
我想要在樹結構中設置表中的數據。從根tsql獲取特定的節點路徑
DECLARE @temp TABLE
(
Id INT
, Name VARCHAR(50)
, Parent INT
)
INSERT @temp
SELECT 1,' Great GrandFather Thomas Bishop', null UNION ALL
SELECT 2,'Grand Mom Elian Thomas Wilson' , 1 UNION ALL
SELECT 3, 'Dad James Wilson',2 UNION ALL
SELECT 4, 'Uncle Michael Wilson', 2 UNION ALL
SELECT 5, 'Aunt Nancy Manor', 2 UNION ALL
SELECT 6, 'Grand Uncle Michael Bishop', 1 UNION ALL
SELECT 7, 'Brother David James Wilson',3 UNION ALL
SELECT 8, 'Sister Michelle Clark', 3 UNION ALL
SELECT 9, 'Brother Robert James Wilson', 3 UNION ALL
SELECT 10, 'Me Steve James Wilson', 3
如何從特定節點的根節點獲取路徑節點?
例如導致了Id IN (2, 5, 10)
是:
Id Result
2 Great GrandFather Thomas Bishop -> Grand Mom Elian Thomas Wilson
5 Great GrandFather Thomas Bishop -> Grand Mom Elian Thomas Wilson -> Aunt Nancy Manor
10 Great GrandFather Thomas Bishop -> Grand Mom Elian Thomas Wilson -> Dad James Wilson -> Me Steve James Wilson
對於一個ID我用這個T-SQL代碼,請完成它:
;WITH cte AS
(
SELECT *, t = 1
FROM @temp
WHERE Id = 10 -- <-- your id
UNION ALL
SELECT t2.*, t + 1
FROM cte t
JOIN @temp t2 ON t.Parent = t2.Id
)
SELECT STUFF((
SELECT ' -> ' + Name
FROM cte
ORDER BY t DESC
FOR XML PATH(''), TYPE).value('.', 'VARCHAR(MAX)'), 1, 4, '')
Go
當我使用FOR XML PATH('')
速度低,怎麼能我沒有使用你的T-SQL代碼?
沒有我的回答解決問題了嗎? – 2013-05-13 09:20:08