1

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.

1 Answer 1

3

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 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.