2013-04-30 2 views
3

내 트리에서 특정 노드의 경로를 가져오고 싶습니다. 내 트리 데이터를보십시오.트리에서 노드 경로 가져 오기

DECLARE @TT TABLE 
(
Id int, 
Name varchar(50), 
Parent int 
) 

INSERT @TT 
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의 경로를 가져올 수 있습니까? ID = 5에 대한 예를 들어, 결과는 다음과 같습니다

Great GrandFather Thomas Bishop -> Grand Mom Elian Thomas Wilson -> Aunt Nancy Manor 
+0

당신이 ID 5. –

+1

안녕을 입력하면 그랜드 삼촌 마이클 주교를 필요 없어요! 도움이되는지 확인하기 http://msdn.microsoft.com/en-us/magazine/cc794278.aspx – Elmer

답변

2

는 시도이 한 -

DECLARE @temp TABLE 
(
     Id INT 
    , Name VARCHAR(50) 
    , Parent INT 
) 

INSERT @temp (Id, Name, Parent) 
VALUES 
    (1, 'Great GrandFather Thomas Bishop', NULL), 
    (2, 'Grand Mom Elian Thomas Wilson' , 1), 
    (3, 'Dad James Wilson',2), 
    (4, 'Uncle Michael Wilson', 2), 
    (5, 'Aunt Nancy Manor', 2), 
    (6, 'Grand Uncle Michael Bishop', 1), 
    (7, 'Brother David James Wilson', 3), 
    (8, 'Sister Michelle Clark', 3), 
    (9, 'Brother Robert James Wilson', 3), 
    (10, 'Me Steve James Wilson', 3) 

;WITH cte AS 
(
    SELECT *, t = 1 
    FROM @temp 
    WHERE Id = 5 -- <-- 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, '') 
2
with data (id, name, parent) as (
    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 
), cte as (
    select *, cast(name as varchar(8000)) as path 
    from data 
    where parent is null 

    union all 

    select d.id, d.name, d.parent, isnull(path + ' -> ', '') + d.name 
    from cte 
    inner join data d on cte.id = d.parent 
) 
select * 
from cte