根据搜索文本删除父记录和子记录

时间:2016-05-19 11:53:14

标签: sql-server tsql sql-server-2014 sql-delete common-table-expression

根据我的应用程序中的搜索文本,我必须以下列格式从表中删除父记录和子记录:

tabItem

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

如果我在我的应用程序内的文本框中键入“信息”并单击“过滤器”,如果树中的最低项包含“信息”,则必须删除每个父项和子项。

树以获得更好的解释:

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

现在我必须删除包含“信息”的项目及其所有父母和祖父母。

我使用以下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 + '%'
)

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

  

声明终止。在语句完成之前,最大递归100已经用尽。

我的cte有什么问题?

1 个答案:

答案 0 :(得分:2)

  

CTE允许最多100次递归

我们可以使用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)