Sql Update Query
13,355
Solution 1
How about
UPDATE T1
SET Address = T2.New_Address
FROM T2
WHERE T1.id = T2.id
Solution 2
UPDATE T1
SET T1.Address = T2.New_Address
FROM T1
INNER JOIN T2 ON T2.ID = T1.ID
Solution 3
UPDATE T1
SET Address = (select New_Address from T2 where T1.ID=T2.ID );
Comments
-
F11 about 2 years
I have a table
T1
which contains three columns:Id, Name, Address
There is another table
T2
which contains 2 columnsId, New_Address
.Id
column ofT2
is same as ofT1
.I need a query which will update
Address
column ofT1
withNew_Address
ofT2
.I can do it through a loop by checking ID and executing update statement. How can it has to be done with a query?
-
ypercubeᵀᴹ over 11 yearsThis - is equivalent to a
LEFT JOIN
and - will also update (setting them toNULL
) all rows in Table1 that do not have aNewAdress
in Table2. -
Martin Smith over 11 years@ypercube - One possible advantage this query does have though is that it will raise an error if there is more than one matching new address rather than silently selecting an undeterministic one. It could be rewritten as
SET Address = ISNULL((select New_Address from T2 where T1.ID=T2.ID ),Address);
thoughMERGE
gives this error checking built in too and would be preferable.