user1694660
user1694660

Reputation: 141

SQL Server Query to fetch nested data

I have a table like this -

declare @tmpData as table
(
MainId int,
RefId int
)

INSERT INTO @tmpData
            (MainId,
             RefId)
VALUES      (1, NULL),
            (2, 1),
            (3, 2),
            (4, 3),
            (5, NULL),
            (6, 5); 

enter image description here

SO, If I pass a value for example - 1 then it should return all rows where value 1 is linked directly or indirectly. And result should be - (Here 1 is ref with MainId 2, and 2 is ref with Main Id 3 and so on...) MaiId 5 and 6 is not related to 1 so output is -

enter image description here

Any one please provide sql server query for the same. Thanks

I tried by applying left join with same table on MainId and RefId. But not got desired output.

Upvotes: 1

Views: 192

Answers (1)

Martin Smith
Martin Smith

Reputation: 453608

You need a recursive CTE (dbfiddle)

WITH R
     AS (SELECT t.MainId,
                t.RefId
         FROM   @tmpData t
         WHERE  t.MainId = 1
         UNION ALL
         SELECT t.MainId,
                t.RefId
         FROM   @tmpData t
                JOIN R
                  ON t.RefId = r.MainId)
SELECT *
FROM   R 

Upvotes: 3

Related Questions