I have a CTE that gets my records recursively.
I now need to delete the records in reverse order (level n - 0) because of the Foreign key constraints.
I am looking at using a cursor from the table it creates but want to use a better method if possible.
The code I am using is following.
******************************
DECLARE @MultipleAnchors TABLE(
ParentID int NULL,
ID int NOT NULL );
INSERT INTO @MultipleAnchors
VALUES
(NULL, 1),
(1, 3),
(1, 4),
(4, 5);
SELECT ParentID, ID
FROM @MultipleAnchors
;WITH MultipleAnchorRowsCTE
AS
(
SELECT ParentID, ID, 0 AS level
FROM @MultipleAnchors
WHERE ParentID IS NULL
UNION ALL
SELECT children.ParentID, children.ID, level + 1
FROM @MultipleAnchors children
JOIN MultipleAnchorRowsCTE AS macte
ON macte.ID = children.ParentID
)
SELECT ParentID, ID, Level
FROM MultipleAnchorRowsCTE;
*************************************************
I was thinking of doing a select/into into a temp table then going through the table in reverse order and delete the records one at a time.
Is there a better way to do that?
Thanks,
Tom
I now need to delete the records in reverse order (level n - 0) because of the Foreign key constraints.
I am looking at using a cursor from the table it creates but want to use a better method if possible.
The code I am using is following.
******************************
DECLARE @MultipleAnchors TABLE(
ParentID int NULL,
ID int NOT NULL );
INSERT INTO @MultipleAnchors
VALUES
(NULL, 1),
(1, 3),
(1, 4),
(4, 5);
SELECT ParentID, ID
FROM @MultipleAnchors
;WITH MultipleAnchorRowsCTE
AS
(
SELECT ParentID, ID, 0 AS level
FROM @MultipleAnchors
WHERE ParentID IS NULL
UNION ALL
SELECT children.ParentID, children.ID, level + 1
FROM @MultipleAnchors children
JOIN MultipleAnchorRowsCTE AS macte
ON macte.ID = children.ParentID
)
SELECT ParentID, ID, Level
FROM MultipleAnchorRowsCTE;
*************************************************
I was thinking of doing a select/into into a temp table then going through the table in reverse order and delete the records one at a time.
Is there a better way to do that?
Thanks,
Tom