How to get the Parent ID of a Parent ID etc?

82 views Asked by At

I got a table with 2 fields:

TableCC.Idx TableCC.RefIdx

The RefIdx field is linking old idx with a new one. I try to obtain the top parent IDx and to show it in a third column.

Example:

Create table TableCC (
    Idx int IDENTITY(1,1) NOT NULL,
    RefIdx int NULL,
    [field giving top parent ID] int NULL
);

INSERT INTO TableCC (Idx,RefIdx,[field giving top parent ID])
VALUES
(1001,1001,1001),
(1002,1002,1002),
(1003,1001,1001),
(1004,1001,1001),
(1005,1004,1001),
(1006,1002,1002),
(1007,1006,1002),
(1008,1007,1002)

Any idea how to obtain something like that?

1

There are 1 answers

0
Tristan Danic On BEST ANSWER

Solution with the help of Mohammad's answer:

    WITH cte AS(
      SELECT Idx,RefIdx , Idx AS topparent 
      FROM CC 
  UNION ALL
      SELECT CC.idx,CC.RefIdx , c.topparent 
      FROM CC JOIN cte c ON c.Idx = CC.RefIdx 
      WHERE CC.Idx <> CC.RefIdx 
)
SELECT * FROM cte