Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find all leaf node records using hierarchyid

How would I go about querying for only records that are "only leaf nodes" (ie. no children)?

I have tried a query like this:

select *
from TableA tt
where tt.HierarchyId.GetDescendant(null, null) not in 
(
    Select  t.HierarchyId
    from TableA t
)

But this still seemed to return some nodes that had children.

I am using the built-in hierarchyid data type (part of ms sqlserver)

like image 835
Marty Avatar asked Oct 20 '25 16:10

Marty


1 Answers

SELECT A.HieracrchyId, A.HierarchyId.ToString()
  FROM dbo.TableA AS A 
  LEFT OUTER JOIN dbo.TableA AS B
  ON A.HierarchyId = B.HierarchyId.GetAncestor(1)
  WHERE B.HierarchyId IS NULL;
like image 149
Aaron Bertrand Avatar answered Oct 23 '25 13:10

Aaron Bertrand