Using a CTE for recurrsion seems like the simplest route to me, here's an example...
DECLARE @people TABLE
(
Id INT,
Name NVARCHAR(50),
ParentId INT
)
INSERT INTO @people (Id, Name, ParentId) VALUES (1, 'Abigail', null)
INSERT INTO @people (Id, Name, ParentId) VALUES (2, 'Ben', 5)
INSERT INTO @people (Id, Name, ParentId) VALUES (3, 'Charlie', 2)
INSERT INTO @people (Id, Name, ParentId) VALUES (4, 'Dave', 1)
INSERT INTO @people (Id, Name, ParentId) VALUES (5, 'Ed', 6)
INSERT INTO @people (Id, Name, ParentId) VALUES (6, 'Frank', null)
;WITH ancestors AS (
SELECT Id, Name, ParentId FROM @people WHERE Id = 3
UNION ALL
SELECT p.Id, p.Name, p.parentId FROM @people p
INNER JOIN ancestors a ON a.parentId = p.Id --This inner join causes the recurrsion
)
SELECT Id, Name, ParentId FROM ancestors
To get from the children to the ancestors switch the ON statement to be the other way arround:
DECLARE @people TABLE
(
Id INT,
Name NVARCHAR(50),
ParentId INT
)
INSERT INTO @people (Id, Name, ParentId) VALUES (1, 'Abigail', null)
INSERT INTO @people (Id, Name, ParentId) VALUES (2, 'Ben', 5)
INSERT INTO @people (Id, Name, ParentId) VALUES (3, 'Charlie', 2)
INSERT INTO @people (Id, Name, ParentId) VALUES (4, 'Dave', 1)
INSERT INTO @people (Id, Name, ParentId) VALUES (5, 'Ed', 6)
INSERT INTO @people (Id, Name, ParentId) VALUES (6, 'Frank', null)
;WITH ancestors AS (
SELECT Id, Name, ParentId FROM @people WHERE Id = 6
UNION ALL
SELECT p.Id, p.Name, p.parentId FROM @people p
--INNER JOIN ancestors a ON a.parentId = p.Id --It was this to go down...
INNER JOIN ancestors a ON a.Id = p.parentId --Now use this to go up the tree
)
SELECT Id, Name, ParentId FROM ancestors