Question

I have a table having records as below:

ID   Name   parentId
1    A      Null
2    B      1
3    C      Null
4    D      3
5    E      4

I need out put in following format

ID   Name   ParentName 

 1    A      Null  
 2    B       A
 3    c      Null
 4    D      C
 5    E      C->D

I tried with following sql query but not able to get exact output. can anybody help me out

With CTE AS
(
   select id, Name, CAST('' AS VARCHAR(MAX)) as Parent from @table
   union All
   select t.Id, t.Name , CTE.Parent+','+CAST(t.Name AS VARCHAR(MAX)) as parents from
   CTE c inner join @table t on t.parentid=c.id and c.parentid is not null
)
select * from cte
Was it helpful?

Solution

Make sure that the anchor is set properly (need to be either the roots or the final leaves). Your current anchor set (the first set from the UNION ALL) is retrieving all records from the table, not just the border ones.

Since your relationships are through parent and not by child, the anchor should contain all records without parents. Then join recursively with each child.

DECLARE @table TABLE (ID INT, name VARCHAR(1), parentID INT)

INSERT INTO @table
VALUES 
    (1, 'A', NULL),
    (2, 'B', 1),
    (3, 'C', NULL),
    (4, 'D', 3),
    (5, 'E', 4)

;With CTE AS
(
    -- Anchor (all grandfathers)
    SELECT
        ID = T.ID,
        Name = T.Name,
        ParentName = CONVERT(VARCHAR(MAX), NULL) -- Set the data type for the UNION
    FROM
        @table AS T
    WHERE
        T.parentId IS NULL

    UNION ALL

    -- Traverse through each children
    SELECT
        ID = T.ID,
        Name = T.Name,
        ParentName = ISNULL(C.ParentName + ' -> ', '') + C.Name
    FROM
        CTE AS C
        INNER JOIN @table AS T ON C.ID = T.parentId
)
SELECT 
    C.*
FROM 
    cte AS C
ORDER BY
    C.ID

Result:

ID  Name    ParentName
1   A       NULL
2   B       A
3   C       NULL
4   D       C
5   E       C -> D
Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top