递归CTE结果是无限的

问题描述 投票:0回答:1

我在 SQL 中有一个表“ActionItem”,其中包含 ActionItemId、ItemName 和 ParentActionItemId 字段。我正在创建一个存储过程,它将接受 ActionItemId (Id) 并递归地显示作为 Id 子项的所有 ActionItem 记录。为此我使用了 CTE。

ALTER PROCEDURE [dbo].[SSP_ActionItem] 
@ActionItemId int
AS
BEGIN   
WITH ActionItemList AS
(
    --  Anchor
    SELECT ActionItem.ActionItemId,
           ActionItem.ItemName,
           ActionItem.ParentActionItemId 
    FROM ActionItem 
    WHERE ActionItemId=@ActionItemId
    
    UNION ALL
    
    --  Recursive query
    SELECT AIL.ActionItemId,
           AIL.ItemName,
           AIL.ParentActionItemId  
    FROM   ActionItem AS AI INNER JOIN  ActionItemList AS AIL 
    ON AI.ParentActionItemId=AIL.ActionItemId

)
SELECT * FROM ActionItemList
--option (maxrecursion 0)
END 

表结构:

   SELECT TOP 1000 [ActionItemId]
    ,[ParentActionItemId]
    ,[ItemName]
    FROM [ActionItem]

这个 sp 返回无限记录。我不明白我哪里出错了。

sql sql-server recursion common-table-expression
1个回答
2
投票

程序应该是:

ALTER PROCEDURE [dbo].[SSP_ActionItem] 
@ActionItemId int
AS
BEGIN   
WITH ActionItemList AS
(
    --  Anchor
    SELECT ActionItem.ActionItemId,
           ActionItem.ItemName,
           ActionItem.ParentActionItemId 
    FROM ActionItem 
    WHERE ActionItemId=@ActionItemId

    UNION ALL

    --  Recursive query
    SELECT AI.ActionItemId,
           AI.ItemName,
           AI.ParentActionItemId  
    FROM   ActionItem AS AI 
    INNER JOIN  ActionItemList AS AIL 
    ON AI.ParentActionItemId=AIL.ActionItemId    
)
© www.soinside.com 2019 - 2024. All rights reserved.