Reputation: 1344
I want to know if theres a better way to script out this update statement:
update table A
set item = (select itemA + ' - ' + itemB from table B where id = 1),
temp = (select itemA from table B where id = 1)
where sid = (select sItemId from table B where id = 1)
Upvotes: 2
Views: 37
Reputation: 1943
SQL Server specific syntax:
update a
set item = b.itemA + ' - ' + b.itemB,
temp = b.itemA
from tableA a
inner join tableB b on a.sid = b.sItemId
where b.id=1
Alternatively you can use MERGE:
merge into tableA as a
using tableB as b
on a.sid = b.sItemId and b.Id = 1
when matched then update set item = b.itemA + ' - ' + b.itemB, temp = b.itemA
;
The advantage of merge is that it is standard SQL syntax, and it will fail if an attempt is made to update the same record twice (the update
with join
will silently do only one of the updates). IIRC in later versions (with the respective compatibility level) update
will fail as well. Also merge
is more flexible.
Upvotes: 1
Reputation: 69494
Use JOINS
to make it more efficient and Alias
to make it more readable.
UPDATE A
SET A.item = B.itemA + ' - ' + B.itemB
,A.temp = B.itemA
FROM tableA A
INNER JOIN tableB B ON A.[sid] = B.sItemId
where B.id = 1
Upvotes: 4
Reputation: 11471
It is of course better to use only one join instead of retrieving the same table (tableB) 3 times
UPDATE tableA
SET tableA.item =tableB. itemA + ' - ' + tableB.itemB,
tableA.temp = tableB.itemA ,
...
FROM tableA, tableB
WHERE tableA.sid= tableB.sItemId And tableB.id =1
Upvotes: 0