Deleting hierarchical data in SQL table

后端 未结 8 2096
遥遥无期
遥遥无期 2020-12-14 09:43

I have a table with hierarchical data.
A column \"ParentId\" that holds the Id (\"ID\" - key column) of it\'s parent.

When deleting a row, I want to delete all c

8条回答
  •  误落风尘
    2020-12-14 10:15

    On SQL Server: Use a recursive query. Given CREATE TABLE tmp(Id int, Parent int), use

    WITH x(Id) AS (
        SELECT @Id
        UNION ALL
        SELECT tmp.Id
          FROM tmp
          JOIN x ON tmp.Parent = x.Id
    )
    DELETE tmp
      FROM x
      JOIN tmp ON tmp.Id = x.Id
    

提交回复
热议问题