【问题标题】:Hierarchyid Problem等级问题
【发布时间】:2010-09-24 13:21:37
【问题描述】:

我有一个带有 hierarchyid 列的表。就像:

[NAME] [PATH]
Ahmet /
Aliye /1/
Selen /1/1/
Erdem /2/
Bilge /2/1/
Aydin /2/2/
Tomrs /2/2/2/

我想看到这样的名字:

[NAMES_WITH_HIERARCHY]
Ahmet
Ahmet/Aliye
Ahmet/Aliye/Selen
Ahmet/Erdem
Ahmet/Erdem/Bilge
Ahmet/Erdem/Aydin
Ahmet/Erdem/Aydin/Tomrs

我该怎么做?

【问题讨论】:

  • 你这样做有什么原因,而不是有一个使用 ID 列专门指出父级的列?每行都有一个 parentID 列;这可能会让事情变得非常简单。
  • 不,我没有理由。我只想使用 HierarcyID……但现在我想我不能使用它。
  • 没有人像这样使用层次结构ID...

标签: sql sql-server hierarchyid


【解决方案1】:

给你:

declare @hierarchy table (name varchar(20), [path] hierarchyid)
insert into @hierarchy ( name, path )
values  
 ('Ahmet', '/')
,('Aliye', '/1/')
,('Selen', '/1/1/')
,('Erdem', '/2/')
,('Bilge', '/2/1/')
,('Aydin', '/2/2/')
,('Tomrs', '/2/2/2/')

--select * from @hierarchy as h

;with Tree([level], [FullName], [path]) as (
    select h.[path].GetLevel() as [level], cast(h.[name] as varchar(max)), h.[path]
    from @hierarchy as h
    where [path] = '/'
    union all
    select h2.[path].GetLevel(), t.[FullName] + '/' + h2.[name] , h2.[path]
    from Tree t
    join @hierarchy as h2 on h2.[path].IsDescendantOf(t.[path]) = 1 and t.[path] <> h2.[path] and h2.[path].GetLevel() - t.[level] < 2 
)
select [Level], cast(FullName as varchar(25)) [Fullname], cast(Path as varchar(10)) [Path] 
from Tree
order by Path

输出:

Level  Fullname                  Path
------ ------------------------- ----------
0      Ahmet                     /
1      Ahmet/Aliye               /1/
2      Ahmet/Aliye/Selen         /1/1/
1      Ahmet/Erdem               /2/
2      Ahmet/Erdem/Bilge         /2/1/
2      Ahmet/Erdem/Aydin         /2/2/
3      Ahmet/Erdem/Aydin/Tomrs   /2/2/2/

【讨论】:

    【解决方案2】:

    这个答案也帮助了我。以为我会添加它发现的改进。 改变

    join @hierarchy as h2 on h2.[path].IsDescendantOf(t.[path]) = 1 and 
                             t.[path] <> h2.[path] and 
                             h2.[path].GetLevel() - t.[level] < 2
    

    JOIN @hierarchy AS h2 ON h2.[path].GetAncestor(1) = t.[path]
    

    将性能从 3 分钟提高到 2 秒,这使其与自引用不分索引。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 2015-02-11
      • 2014-09-20
      • 1970-01-01
      • 2021-05-22
      • 2020-10-22
      • 1970-01-01
      相关资源
      最近更新 更多