用于递归查询的CTE

时间:2018-02-09 07:38:21

标签: sql sql-server common-table-expression recursive-query

我试图使用CTE来查询分层数据但我仍然坚持以下情况。 我的数据库中有以下数据:

dbo.ProjectComponents

Id
207

dbo.ProjectAccessories

Id  ProjectComponentId  AccessorySetId
4   34                  NULL
5   145                 NULL
6   207                 NULL
8   NULL                3

dbo.ProjectAccessorySets

Id  AccessoryId
1   NULL
2   NULL
3   6

我想查询ProjectComponent的所有dbo.ProjectAccessory.Id。

以下查询引发此错误:Error 530: The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

WITH AccessoryIds AS
(SELECT parent.Id, accessorySets.AccessoryId
FROM dbo.ProjectAccessories AS parent, dbo.ProjectAccessorySets AS accessorySets
WHERE parent.ProjectComponentId = 207 AND accessorySets.AccessoryId = parent.Id
UNION ALL
SELECT child.Id, childAccessorySets.AccessoryId
FROM dbo.ProjectAccessories AS child, dbo.ProjectAccessorySets AS childAccessorySets
INNER JOIN AccessoryIds AS asi ON childAccessorySets.AccessoryId = asi.Id
WHERE childAccessorySets.AccessoryId = child.Id AND childAccessorySets.AccessoryId IS NOT NULL)
SELECT * FROM AccessoryIds

预期输出

Id  AccessoryId
6   NULL
8   6

修改

添加option (maxrecursion 0)并未解决问题,并使de query永远运行。接下来,我的数据库中的递归深度目前只有2(参见附加数据)

1 个答案:

答案 0 :(得分:1)

看起来会这样做:

@Order(Ordered.HIGHEST_PRECEDENCE), @Priority

结果:

DECLARE @ProjectAccessories TABLE
(
    Id INT, ProjectComponentId INT, AccessorySetId INT 
)
DECLARE @ProjectAccessorySets TABLE
(
    Id INT, AccessoryId INT
)

INSERT @ProjectAccessories (Id, ProjectComponentId, AccessorySetId)
VALUES (4, 34, NULL)
,       (5, 145, NULL)
,       (6, 207, NULL)
,       (8, NULL, 3)

INSERT @ProjectAccessorySets (Id, AccessoryId)
VALUES (1, NULL)
,       (2, NULL)
,       (3, 6) 

;
WITH AccessoryIds AS
(
        SELECT      parent.Id
        ,           parent.AccessorySetId AS AccessoryId
        FROM        @ProjectAccessories AS parent
        INNER JOIN  @ProjectAccessorySets AS accessorySets
                ON  accessorySets.AccessoryId = parent.Id
        WHERE       parent.ProjectComponentId = 207

        UNION ALL

        SELECT      child.id
        ,           childAccessorySets.AccessoryId
        FROM        AccessoryIds AS asi 
        INNER JOIN  @ProjectAccessorySets AS childAccessorySets
                ON  childAccessorySets.AccessoryId = asi.Id
        INNER JOIN  @ProjectAccessories AS child
                ON  child.AccessorySetId = childAccessorySets.id
)

SELECT  * 
FROM    AccessoryIds