这是一个有趣的层次结构。似乎允许父母成为他们孩子的孩子。如果发生这种情况,则此代码逻辑将中断,但只要不发生这种情况,它就应该起作用。
Create Function dbo.IdentifyHierarchyPaths (@DeepestChildNode UniqueIdentifier)
Returns @hierarchy Table
(
Hierarchy Varchar(Max)
)
As
Begin
;With BuildHier As
(
Select Convert(Varchar(Max),h2.ChildCategoryId) As child, Convert(Varchar(Max),h1.ChildCategoryId) + ' > ' + Convert(Varchar(Max),h2.ChildCategoryId) As hier
From Hierarchy h1
Left Join Hierarchy h2
On h1.ChildCategoryId = h2.ParentCategoryId
Where h1.ParentCategoryId Is Null
Union All
Select Convert(Varchar(Max),h1.ChildCategoryId) As child, bh.hier + ' > ' + Convert(Varchar(Max),h1.ChildCategoryId) As hier
From BuildHier bh
Join Hierarchy h1
On bh.child = h1.ParentCategoryId
), HierWithTopLevel As
(
Select Convert(Varchar(Max),ChildCategoryId) As hierarchy
From Hierarchy
Where ParentCategoryId Is Null
Union
Select hier
From BuildHier
)
Insert @hierarchy
Select hierarchy
From HierWithTopLevel
Where Right(hierarchy,36) = Convert(Varchar(36),@DeepestChildNode);
Return;
End;