SQL 2008 HierarchyID - Select X descendants down
How can I query a table which has a column of data type HIERARCHYID and get a list of descendants X levels deep under an employee?
Here is the current structure:
CREATE TABLE [dbo].[Employees]开发者_StackOverflow中文版(
[NodeId] [hierarchyid] NOT NULL,
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[FirstName] [varchar](120) NULL,
[MiddleInitial] [varchar](1) NULL,
[LastName] [varchar](120) NULL,
[DepartmentId] [int] NULL,
[Title] [varchar](120) NULL,
[PhoneNumber] [varchar](20) NULL,
[IM] [varchar](120) NULL,
[Photo] [varbinary](max) NULL,
[Bio] [varchar](400) NULL,
[Active] [bit] NULL,
[ManagerId] [int] NULL
)
I wanted to add a little to the above. In addition to selecting a branch of a tree, you often want descendants of only a certain depth. To accomplish this, many tables using add an additional computed column for "depth" ( something like [Depth] AS (myHierarchy.GetLevel]()
). With this extra column you can run queries like the following to limit by depth.
SELECT @MaxDepth = 3,
SELECT @theParent = Hierarchy,
@theParentDepth = Depth
FROM myTreeTable T
WHERE T.RowID = @RowID
SELECT myHierarchy
FROM myTreeTable T
WHERE T.myHierarchy.IsDescendantOf(@theParent) = 1 AND
T.Depth < (@theParentDepth + @MaxDepth)
Note, you may want to index the computed column (probably combined with or including some other columns) if you are relying on it heavily.
精彩评论