I’m writing a query to update a table(TableA) use the value from another table (TableB), table B returns more than one value against each row in TableA and the request is to update with the biggest return value in TableB.
I can achieve this by:
UPDATE TableA
SET Value = (SELECT TOP 1 B.Value FROM dbo.TableB B
WHERE TableA.Key = B.Key
ORDER BY B.Value desc)
I’m not sure it is the best way to achieve the require, moreover I worry about the performance of the above query. Does it scan multiple times on Table B to find the value for each row of Table A?
I tried some query e.g. use
update tableA
set Value = TableB.Value
from (Table A left join Table B ... where ...)
I think the second one may have a better performance, but I cannot retrieve the biggest value, since it doesn’t support “order by".
Join Table B twice and compare the B’s values may solve the problem, but the perform could worse than the first query.
Any ideas?
** the real situation is complex than the example, e.g. tableA and tableB need to join on “….or….or…or…”, will cost more.
The examples you gave use correlated suqueries, so for each row in A the sub-query will be executed. You can avoid a correlated subquery by using TableA twice in your query, something like