我在 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 返回无限记录。我不明白我哪里出错了。
程序应该是:
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
)