我在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返回无限的记录。我不明白我哪里出错了。有人可以帮忙吗?我是这个CTE概念的新手。
答案 0 :(得分: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
)