Search code examples
sqlsql-serverrdbmscascading-deletes

delete all the child rows in sql table by parentid


I have a table from which I create a tree with multiple levels and parents. The table structure looks like this.

enter image description here

When I delete the "TitleID", I want all the children and even the grandchildren to be deleted. What is the easiest way to do such in sql. If I simple delete with "where ParentID=TitleID", only children with level 1 depth are deleted.


Solution

  • DECLARE @TitleId INT 
    
    SELECT @@TitleId = 2 
    
    ;WITH results AS( 
            SELECT  TitleId
            FROM    myTable 
            WHERE   TitleId = @TitleId 
            UNION ALL 
            SELECT  t.TitleId 
            FROM    myTable t 
                    INNER JOIN ret r ON t.ParentID = r.TitleId
    ) 
    
    DELETE FROM myTable WHERE TitleId IN (SELECT TitleId FROM    results )