2010-09-24 9 views
2

J'ai une table avec une colonne hierarchyid. Il est comme:Hierarchyid Problème

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

Je veux voir des noms comme:

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

Comment puis-je faire cela?

+1

Y a-t-il une raison pour que vous le fassiez comme cela plutôt que d'avoir une colonne qui pointe spécifiquement le parent en utilisant une colonne ID? J'aurais une colonne parentID pour chaque rangée; ce qui rendrait probablement très simple. – Josh

+0

Non, je n'ai aucune raison. Je voulais utiliser HierarcyID seulement ... mais maintenant je pense que je ne peux pas l'utiliser. – ogun

+0

Personne n'utilise l'id de hierarcy comme ceci ... – ogun

Répondre

3

Ici, vous allez:

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 

Sortie:

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/ 
+0

merci, denis! :) – ogun

3

Cette réponse m'a aidé aussi. Je pensais que j'ajouterais une amélioration. Modification

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] 

performances accrues de 3 min à 2 sec, ce mettre sur pied d'égalité avec auto-référencement indépendamment de l'indexation.