I want to update multiple records however the value being set is based on the primary key of the given record. This is not an issue with a single record as I can use:
UPDATE T1
SET A1 = (SELECT TOP 1 X FROM T2 WHERE Y = ID1)
WHERE A2 = ID1
The IN operator works fine for the WHERE clause as it will update the correct list but not in the sub query. In the SET it will get the top 1 from all values in the ID list and I just want it for that corresponding record/ID.
Using: Microsoft T-SQL
Thank You
Best Answer
Instead of specifying the same IN list for both
Y
andA2
, specify it only forA2
and make the subquery correlate withT1
onT2.Y = T1.A2
, like this:This way the subquery will pick the topmost row from
T2
that matches the key of theT1
row being updated.Please note also that using
TOP n
withoutORDER BY
will result in an arbitrary row being selected. If there can be two or more distinct values ofX
perY
inT2
, it might be a good idea to make the results deterministic by introducing anORDER BY
clause with specific enough set of sorting criteria.On the other hand, if
X
stays the same perY
, you are probably storing redundant information inT2
. Perhaps, in that case you should move theX
column toT1
, based on the facts that a)T2.Y
appears to be a reference toT1.A2
and b)A2
is the primary key ofT1
.