如何使用SQL Server 2008 hierarchyid获取节点的所有祖先?

时间:2010-06-25 16:55:10

标签: sql-server hierarchyid

给定一个带有hierarchyid类型列的表,如何编写查询以返回作为特定节点祖先的所有行?

有一个IsDescendantOf()函数,这对于让孩子们来说是完美的,但是没有相应的IsAncestorOf()函数来返回祖先(并且缺少GetAncestors()函数看起来很像监督。)

6 个答案:

答案 0 :(得分:29)

最常用的方法是递归公用表表达式(CTE)

WITH Ancestors(Id, [Name], AncestorId) AS
(
      SELECT
            Id, [Name], Id.GetAncestor(1)
      FROM
            dbo.HierarchyTable
      WHERE
            Name = 'Joe Blow'  -- or whatever you need to select that node

      UNION ALL

      SELECT
            ht.Id, ht.[Name], ht.Id.GetAncestor(1)
      FROM
            dbo.HierarchyTable ht
      INNER JOIN 
            Ancestors a ON ht.Id = a.AncestorId
)
SELECT *, Id.ToString() FROM Ancestors

(改编自Simon Ince blog post

Simon Ince还提出了第二种方法,他只是基本上改变了条件 - 而不是检测那些作为目标人的祖先的人条目,他转过来检查:

DECLARE @person hierarchyid

SELECT @person = Id
FROM dbo.HierachyTable
WHERE [Name] = 'Joe Blow';

SELECT
    Id, Id.ToString() AS [Path], 
    Id.GetLevel() AS [Level],
    Id.GetAncestor(1),
    Name
FROM 
    dbo.HierarchyTable
WHERE 
    @person.IsDescendantOf(Id) = 1

这将从您的表中选择所有行,您感兴趣的目标人员是层次结构中任何级别的后代。因此,这将找到目标人物的直接和非直接祖先一直到根。

答案 1 :(得分:14)

以下是一个回答:

SELECT t1.Id.ToString() as Path, t1.Name
    FROM (SELECT * FROM HierarchyTable
        WHERE Name = 'Joe Blow') t2,
    HierarchyTable t1
    WHERE t2.Id.IsDescendantOf(t1.Id) = 1

答案 2 :(得分:3)

Declare @hid hierarchyid=0x5D10 -- Child hierarchy id

SELECT
*
FROM 
  dbo.TableName
WHERE 
  @hid.IsDescendantOf(ParentHierarchyId) = 1

答案 3 :(得分:1)

我编写了一个用户定义的表值函数,它将hierarchyid值扩展为其组成祖先。然后可以将输出连接回hierarchyid列以专门获取这些祖先。

alter function dbo.GetAllAncestors(@h hierarchyid, @ReturnSelf bit)
returns table
as return
 select @h.GetAncestor(n.Number) as h
 from dbo.Numbers as n
 where n.Number <= @h.GetLevel()
  or (@ReturnSelf = 1 and n.Number = 0)

 union all

 select @h
 where @ReturnSelf = 1
go

开始使用它:

select child.ID, parent.ID
from dbo.yourTable as child
cross apply dbo.GetAllAncestors(child.hid, 1) as a
join dbo.yourTable as parent
   on parent.hid = a.h

答案 4 :(得分:0)

完善 Ben Thui 的答案,我认为这是迄今为止最好的答案...

下面的方法允许在一次查询中不仅检索一个,而且可能检索多个叶行及其后代。

Create Or Alter Function dbo.GetAllAncestors
(
    @Path       HierarchyId,
    @WithSelf   Bit = 1,
    @MinLevel   Int = 0,
    @MaxLevel   Int = Null
)
Returns Table
As
Return

With Ancestor As
(
    Select  @Path As Path
    Union All

    Select  Path.GetAncestor(1)
    From    Ancestor
    Where   Path.GetLevel() > 0
)

Select  Path, Path.GetLevel() As Level
From    Ancestor
Where   (@WithSelf = 1 Or Path <> @Path)
And     Path.GetLevel() >= Case When @MinLevel < 0 Or @MinLevel Is Null Then 0 Else @MinLevel End
And     (@MaxLevel Is Null Or Path.GetLevel() <= @MaxLevel)

使用:

-- This assumes the table has a Path HierarchyId colum, and the values are unique and indexed.

-- If you know the path
Select *
From MyTable
Where Path In
(
    Select Path From dbo.GetAllAncestors(@ThePath, Default, Default, Default)
)

-- If you don't know the path
Select *
From MyTable t1
Where Path In 
(
    Select Path
    From   MyTable t2
           Cross Apply dbo.GetAllAncestors(t2.Path, Default, Default, Default)
    Where  /* Find the leaf record(s) here.
              Note that if multiple rows match, they will all be returned as well as their parents in a single roundtrip. */
)

答案 5 :(得分:-1)

public function __construct()
    {
        $this->middleware('auth')->except(['yourFunctionName']);
    }