BEGIN TRAN UPDATE sp SET ParentID = 1 FROM SectionParents AS sp WITH (HOLDLOCK TABLOCKX) WHERE 1 = 0 TRUNCATE TABLE SectionParents ;WITH cte AS ( SELECT ID AS ParentID, ID FROM dbo.Section UNION ALL SELECT c.ParentID, s.ID FROM cte AS c INNER JOIN dbo.Section AS s ON s.spRef = c.ID WHERE s.ID <> s.spRef) INSERT INTO SectionParents(ParentID, ID) select * from cte COMMIT