I have a situation where I need to configure existing client data to solve a problem when our application incorrectly updated identifiers in a table, when it should have been.
Here is the script. We have a parent table in which rows can be inserted that effectively replace existing rows; replacement can be recursive. We also have a child table in which there is a field pointing to the parent table. In existing data, the child table can point to rows that have been replaced, and I need to fix this. However, I cannot simply update each line to a replacement line, because this line could also be replaced, and I need the last line to be displayed.
I was trying to find a way to write a CTE that would accomplish this for me, but I am struggling to find a query that finds what I'm actually looking for. Here is an example of a table I'm working with; the “ShouldBe” column is what I would like my update request to end, taking into account the recursive replacement of some rows.
DECLARE @parent TABLE (SampleID int, SampleIDReplace int, GroupID char(1)) INSERT INTO @parent (SampleID, SampleIDReplace, GroupID) VALUES (1, -1, 'A'), (2, 1, 'A'), (3, -1, 'A'), (4, -1, 'A'), (5, 4, 'A'), (6, 5, 'A'), (7, -1, 'B'), (8, 7, 'B'), (9, 8, 'B') DECLARE @child TABLE (ChildID int, ParentID int) INSERT INTO @child (ChildID, ParentID) VALUES (1, 4), (2, 7), (3, 1), (4, 3)
Desired results in the child table after applying the update script:
ChildID ParentID ParentID_ShouldBe 1 4 6 (4 replaced by 5, 5 replaced by 6) 2 7 9 (7 replaced by 8, 8 replaced by 9) 3 1 2 (1 replaced by 2) 4 3 3 (unchanged, never replaced)