Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
506 views
Welcome To Ask or Share your Answers For Others

1 Answer

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...