如何获取父ID等的父ID?

时间:2018-02-09 13:04:24

标签: sql sql-server-2012

我有一张包含2个字段的表格:

TableCC.Idx TableCC.RefIdx

RefIdx字段将旧idx与新idx相关联。我尝试获取顶级父IDx并在第三列中显示它。

示例:

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)

知道如何获得这样的东西吗?

1 个答案:

答案 0 :(得分:0)

在穆罕默德回答的帮助下解决:

    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