【问题标题】:Get path of node in tree获取树中节点的路径
【发布时间】:2013-04-30 16:59:21
【问题描述】:

我想获取树中特定节点的路径。请查看我的树数据。

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

【问题讨论】:

标签: sql-server tsql tree


【解决方案1】:

试试这个 -

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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-12-06
      • 2016-08-16
      • 1970-01-01
      • 2011-07-12
      • 2016-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多