I have a table from which I create a tree with multiple levels and parents. The table structure looks like this.
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.
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 )