Deleting hierarchical data in SQL table

后端 未结 8 2097
遥遥无期
遥遥无期 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:18

    Depends on your database. If you are using Oracle, you could do something like this:

    DELETE FROM Table WHERE ID IN (
      SELECT ID FROM Table
      START WITH ID = id_to_delete
      CONNECT BY PRIOR.ID = ParentID
    )
    

    ETA:

    Without CONNECT BY, it gets a bit trickier. As others have suggested, a trigger or cascading delete constraint would probably be easiest.

提交回复
热议问题