Is there any difference between these two simple SQL Update statements?
UPDATE table1
SET col = 1
WHERE col2 = 'xyz'
UPDATE a
SET col = 1
FROM table1 a
WHERE col2 = 'xyz'
Which is preferable?
The only difference I could figure out was that the second statement allows WITH NO LOCK to be used next to the FROM clause. But when used next to the update operator, it gives the same error message as in the first statement
NOLOCK and READUNCOMMITTED lock hints are not allowed on the target tables of INSERT, UPDATE, or DELETE statements.
Many thanks
+3
source to share
4 answers
They are the same.
If the UPDATE statement only includes access to one table, the former is cleaner / simpler.
If you need to do, for example, a JOIN and then an alias assignment for your second example is a purge (IMO) like:
UPDATE a
SET a.Col = 1
FROM TableA a
JOIN TableB b ON a.Id = b.Id
WHERE b.Something = '123'
By the way, it doesn't make sense to have a NOLOCK hint on the table being updated, so don't take that as a reason for one over the other.
+3
source to share