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
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:
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With