I'm trying to find a way to get all ancestor nodes of a given node using HierarchyID. Every solution I've seen using HierarchyID seems to use either a CTE or a variable. Is there a way to do this using a single select statement?
To make things simpler:
CREATE TABLE Employee
(
EmpId INT PRIMARY KEY IDENTITY,
EmpName VARCHAR(100) NOT NULL,
Position HierarchyID NOT NULL
)
INSERT INTO Employee (EmpName, Position)
VALUES ('CEO', '/'),
('COO', '/1/'),
('CIO', '/2/'),
('CFO', '/3/'),
('VP Financing', '/3/1/'),
('Accounts Receivable', '/3/1/1/'),
('Accountant 1', '/3/1/1/1/'),
('Accountant 2', '/3/1/1/2/'),
('Accountant 3', '/3/1/1/3/'),
('Accounts Payable', '/3/1/2/'),
('Accountant 4', '/3/1/2/1/'),
('Accountant 5', '/3/1/2/2/'),
('DBA', '/2/1/'),
('VP of Operations', '/1/1/')
Best Answer
To get "all parent nodes of a given node":
but there will only ever be one due to the nature of hierarchies.
If you really want to get all immediate children nodes of a given node:
-- EDIT
I see that you want all ancestor nodes. Perhaps try an approach like this:
or
here is a CTE method for comparison: