I have two tables with parent / child relationship. I want to update the parent with data from the child. However, assuming there are 2 children, I would like to be able to choose which child is used to update, depending on the other column from the child. Here is what I have so far: Parent: @test Child: @exdat Expected result, the result of the parent after the update should contain only uppercase letters. I want to update a parent with some data from a child, but if more than one exists, I would prefer to select a child with dimp p1 over p2, p2 over p3 and p3 over p4
DECLARE @test TABLE ( id int, val char(1) ); DECLARE @exdat TABLE ( id int, dval char(1), dimp char(2) ); INSERT INTO @test (id,val) SELECT 1,'a' UNION ALL SELECT 2,'b' UNION ALL SELECT 3,'c' UNION ALL SELECT 4,'d' UNION ALL SELECT 5,'e' UNION ALL SELECT 6,'f' UNION ALL SELECT 7,'g' ; INSERT INTO @exdat (id,dval,dimp) SELECT 1,'A','p1' UNION ALL SELECT 2,'B','p3' UNION ALL SELECT 3,'C','p1' UNION ALL SELECT 4,'D','p2' UNION ALL SELECT 5,'E','p2' UNION ALL SELECT 6,'F','p3' UNION ALL SELECT 7,'w','p2' UNION ALL SELECT 7,'g','p3' UNION ALL SELECT 7,'G','p1' UNION ALL SELECT 7,'z','p4' ; UPDATE @test SET val = e.dval FROM @test t INNER JOIN @exdat e ON t.id = e.id ; SELECT * FROM @test; Result: 1 A 2 B 3 C 4 D 5 E 6 F 7 w <-- problem illustrated here
This "w" could be any of the values w, g, G, z. So I ask, how do I prioritize a child’s choice based on another column?