首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >层次化问题

层次化问题
EN

Stack Overflow用户
提问于 2010-09-24 21:21:37
回答 2查看 727关注 0票数 2

我有一个包含hierarchyid列的表。它类似于:

代码语言:javascript
复制
[NAME] [PATH]
Ahmet /
Aliye /1/
Selen /1/1/
Erdem /2/
Bilge /2/1/
Aydin /2/2/
Tomrs /2/2/2/

我希望看到这样的名称:

代码语言:javascript
复制
[NAMES_WITH_HIERARCHY]
Ahmet
Ahmet/Aliye
Ahmet/Aliye/Selen
Ahmet/Erdem
Ahmet/Erdem/Bilge
Ahmet/Erdem/Aydin
Ahmet/Erdem/Aydin/Tomrs

我该怎么做呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2010-09-24 22:49:03

这就是了:

代码语言:javascript
复制
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

输出:

代码语言:javascript
复制
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/
票数 3
EN

Stack Overflow用户

发布于 2011-11-17 03:24:29

这个答案也帮了我大忙。我想我会添加一个它发现的改进。改变

代码语言:javascript
复制
join @hierarchy as h2 on h2.[path].IsDescendantOf(t.[path]) = 1 and 
                         t.[path] <> h2.[path] and 
                         h2.[path].GetLevel() - t.[level] < 2

代码语言:javascript
复制
JOIN @hierarchy AS h2 ON h2.[path].GetAncestor(1) = t.[path]

将性能从3分钟提高到2秒,这使其与自引用不相上下,无论索引如何。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3787486

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档