无法使用递归CTE找到匹配的子记录

时间:2012-06-26 11:11:23

标签: sql-server-2008 recursive-cte

我有下表@t:

ParentId   SkuName  ChildId
   P1         X1      C1
   C1         X2      C2
   C2         X3      C2

如果我传递ParentId = P1,则所需的输出为x3

即。停止条件是匹配记录的最后一行,并获取该

的sku名称

行。如果没有匹配的行,则返回null

我的尝试(虽然没有工作)

DECLARE @t TABLE (ParentId Varchar(100), Name VARCHAR(20), ChildId Varchar(100))
INSERT INTO @t(ParentId, Name, ChildId)
  SELECT 'P1', 'X1', 'C1' UNION ALL
  SELECT 'C1', 'X2', 'C2' UNION ALL
  SELECT 'C2', 'X3', 'C2' 

Declare @ParentId Varchar(10) = 'P1'

;With CTE As
(
    Select 
        Rn = ROW_NUMBER() Over(Order By (Select 1))
        ,ParentId
        , Name
        , ChildId
    From @t Where ParentId = @ParentId

    Union All

    Select 
        Rn + 1
        ,pc.ParentId as Parents     
        ,pc.Name
        ,pc.ChildId
    FROM @t pc
    JOIN CTE gp on pc.Childid = gp.Parentid
)

Select *
From CTE

请帮忙

1 个答案:

答案 0 :(得分:0)

问题在于您的第二个JOIN查询中的UNION。您正在加入pc.Childid = gp.Parentid。你应该加入pc.ParentId = gp.Childid

此外,由于您的数据同时将child和parent都设置为相同的值,因此除非指定在ParentId等于Childid时递归应该停止,否则最终将无限递归。 (WHERE gp.ParentId <> gp.Childid

这是您正在寻找的结果吗?

DECLARE @t TABLE (ParentId VARCHAR(100), Name VARCHAR(20), ChildId VARCHAR(100))
INSERT INTO @t(ParentId, Name, ChildId)
SELECT 'P1', 'X1', 'C1' UNION ALL
SELECT 'C1', 'X2', 'C2' UNION ALL
SELECT 'C2', 'X3', 'C2' 

DECLARE @ParentId VARCHAR(10) = 'P1'

;With CTE As
(
    SELECT 
        Rn = 1
        ,ParentId
        ,Name
        ,ChildId
    FROM @t WHERE ParentId = @ParentId

    UNION All

    SELECT 
        Rn + 1
        ,pc.ParentId as Parents     
        ,pc.Name
        ,pc.ChildId
    FROM @t pc
    JOIN CTE gp 
        on pc.ParentId = gp.Childid
    WHERE gp.ParentId <> gp.Childid
)

SELECT TOP 1 *
FROM CTE
ORDER BY Rn DESC
OPTION (MAXRECURSION 0);