Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursively find all ancestors given the child

Tags:

sql-server

Given a child id, I need to return a query containing all parents of that child as well as their parents till I get to the root parent. For example, given this data:

ID / Parent ID
1  /  0
2  /  1
3  /  2
4  /  0
5  /  3

So if I passed in ID 5 I would like to get a query with the results:

ID / Parent ID
1  /  0
2  /  1
3  /  2

This table does not work with a hierarchyid type so I suspect that this will need to be done with a CTE, but have no clue how. If it can be done in an SQL query / proc, any help would be appreciated.

Thanks

like image 724
Paolo Broccardo Avatar asked Jul 22 '12 08:07

Paolo Broccardo


1 Answers

This is more or less what you want:

-- CTE to prepare hierarchical result set
;WITH #results AS
(
    SELECT  id, 
            parentid 
    FROM    [table] 
    WHERE   id = @childId
    UNION ALL
    SELECT  t.id, 
            t.parentid 
    FROM    [table] t
            INNER JOIN #results r ON r.parentid = t.id
)
SELECT  *
FROM    #results;

Reference:

  • CTE: Common Table Expression

Working example:

-- create table with self lookup (parent id)
CREATE TABLE #tmp (id INT, parentid INT);

-- insert some test data
INSERT INTO #tmp (id, parentid) 
SELECT 1,0 UNION ALL SELECT 2,1 UNION ALL SELECT 3,2
UNION ALL SELECT 4,0 UNION ALL SELECT 5,3;

-- prepare the child item to look up
DECLARE @childId INT;
SET @childId = 5;

-- build the CTE
WITH #results AS
(
    SELECT  id, 
            parentid 
    FROM    #tmp 
    WHERE id = @childId
    UNION ALL
    SELECT  t.id, 
            t.parentid 
    FROM    #tmp t
            INNER JOIN #results r ON r.parentid = t.id
)

-- output the results
SELECT  * 
FROM    #results 
WHERE   id != @childId 
ORDER BY id;

-- cleanup
DROP TABLE #tmp;

Output:

1 | 0
2 | 1
3 | 2

like image 100
Paul Fleming Avatar answered Oct 16 '22 07:10

Paul Fleming