根据搜索文本删除 parent 和 child 条记录

Delete parent and child records depending on search text

根据我应用程序中的搜索文本,我必须按照以下格式从 table 中删除 parent 和 child 记录:

tabItem

+--------+--------------+----------+-----------------+
| ItemId | ItemParentId | ItemName | ItemDescription |
+--------+--------------+----------+-----------------+

如果我在应用程序内的文本框中键入 "information" 并单击 "Filter",我必须删除每个 parent 和 child 项(如果最低)树中的项目包含 "information".

更好解释的树:

Category 1
|
+--- Subcategory
     |
     +--- Subsubcategory
          |
          +--- Item (contains "information" in ItemDescription)
Category 2
|
+--- Subcategory
     |
     +--- Subsubcategory
          |
          +--- Item (doesn't contain "information")

现在我必须删除包含 "information" 的项目,所有项目都是 parents 和 grandparents。

我尝试使用以下 cte:

WITH cte_toDelete
AS
(
    SELECT *
    FROM tabItem
    UNION ALL
    SELECT cte_toDelete.*
    FROM cte_toDelete
    INNER JOIN tabItem ON cte_toDelete.ItemParentId = tabItem.ItemId
)
DELETE FROM tabItem
WHERE ItemId IN
(
    SELECT ItemId
    FROM cte_toDelete
    WHERE cte_toDelete.ItemName NOT LIKE '%' + @SearchText + '%'
    AND cte_toDelete.ItemDescription NOT LIKE '%' + @SearchText + '%'
)

但是当我 运行 这些行时,我得到以下错误:

The statement terminated. The maximum recursion 100 has been exhausted before statement completion.

我的 cte 怎么了?

CTE allows The maximum 100 recursion only

我们可以使用 MAXRECURSION 更改其设置,MAXRECURSION 的值可以在 0 到 32,767 之间

了解更多信息MAXRECURSION

WITH cte_toDelete
AS
(
   SELECT *
   FROM tabItem
   UNION ALL
   SELECT cte_toDelete.*
   FROM cte_toDelete
   INNER JOIN tabItem ON cte_toDelete.ItemParentId = tabItem.ItemId
)
DELETE FROM tabItem
WHERE ItemId IN
(
  SELECT ItemId
  FROM cte_toDelete
  WHERE cte_toDelete.ItemName NOT LIKE '%' + @SearchText + '%'
  AND cte_toDelete.ItemDescription NOT LIKE '%' + @SearchText + '%'
 )
 OPTION (MAXRECURSION 0)