Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find ALL descendants using HierarchyID for SQL Server

I need to find all descendants of a category using HierarchyID for SQL Server.

I know how to find direct children but I would like to find children of children of children and so on.

Is there a way to do this using the HierarchyID?

like image 300
Luke101 Avatar asked Apr 17 '10 19:04

Luke101


1 Answers

If you have the root of the tree you want, can't you just use:

DECLARE @root hierarchyID;

SELECT @root = col
FROM yourTable
WHERE [whatever uniquely identifies this row]

SELECT *
FROM yourTable
WHERE col.IsDescendantOf(@root) = 1
like image 54
Marc Gravell Avatar answered Sep 28 '22 02:09

Marc Gravell