I have seen examples of updating multiple rows from a join, but in this case there are more than one matching rows resulting from a join, I need a specific row (the earliest UpdatedDate row).
Example of the tables:
[Robot]
RobotNumber RobotName RobotColor UpdatedDate 1 XA01 Red 01/01/2020 2 B1205 Purple 02/02/2020 3 ZP344 Orange 03/03/2020
[RobotAuditTable]
RobotNumber RobotName RobotColor UpdatedDate 1 XA01 Yellow 1/1/2019 1 XA01 Red 2/2/2020
I want to update the RobotName XA01 with the values(RobotName, RobotColor) from the earliest Updated Date row in the RobotAuditTable.
I have tried approaches with joins and subqueries but I cannot get the syntax and conditions correct.
Advertisement
Answer
You can use apply
:
update r set r.robotname = rat.robotname, r.robotcolor = rat.robotcolor from robot r cross apply (select top (1) rat.* from robotaudittable rat where rat.robotnumber = r.robotnumber order by rat.updateddate asc ) rat;