Deleting rows recursively in a self-referencing table using a CTE. How does the process take place?

拥有回忆 提交于 2019-12-06 00:51:38

问题


I'm working on a side project, and in order to delete a row and all its descendants in a self-referencing table, I'm using a recursive CTE like this inside a trigger:

CREATE TRIGGER dbo.tr_Comment_Delete
    ON dbo.Comment INSTEAD OF DELETE
AS
    ;WITH IDs AS (
       SELECT id FROM DELETED
       UNION ALL
       SELECT c.id
       FROM Comment AS c INNER JOIN IDs AS i 
        ON c.parent_comment_id = i.id
    )
    DELETE FROM Comment
    WHERE id IN (SELECT id FROM IDs);
GO

This is the self-referencing table

Although I have this code working as expected, it is one of those cases in which you do something, but you're not quite sure how it works.

To be more precise, what I'd like to know is how it is that by using this recursive CTE(IDs) I'm able to avoid referential integrity errors when I try to delete a comment that has child comments?

What is it the process/order in which the comments are deleted?

Take this hierarchy of comments as an example:

3-> 8-> 13 

Here the comment of id 3 is the root comment. Comment 8 is a reply to comment 3,just like comment 13 is a reply to comment 8.

How does the deletion process actually take place?

P.S. I tried adding a table in which I inserted the Ids as they were calculated. Unfortunately I can't make sense of it. These are the results of such table:

id  ins-date
3   2017-09-12 11:48:38.037
8   2017-09-12 11:48:38.037
13  2017-09-12 11:48:38.037
13  2017-09-12 11:48:38.037
8   2017-09-12 11:48:38.037
13  2017-09-12 11:48:38.037

回答1:


I suppose you see complexity where it does not exists.

Your mistake is:

Deleting rows recursively in self-referencing CTE

There is no such thing as recursive DELETE. Only SELECT can be.

So processing is simple as:

  1. Calculate all rows for deletion in SELECT with recurcive CTE

  2. DELETE them all with one operation

That's all



来源:https://stackoverflow.com/questions/46185846/deleting-rows-recursively-in-a-self-referencing-table-using-a-cte-how-does-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!