Wednesday, July 15, 2009

batch update on a table from another table

CREATE TABLE A
(
NAME VARCHAR2(20 BYTE),
AGE INTEGER
)

CREATE TABLE B
(
NAME VARCHAR2(20 BYTE),
AGE INTEGER
)

Suppose we need to update the age of table B with the age of table A.

For oracle the command will be -

UPDATE tmp_B b
SET age = (SELECT a.age FROM tmp_A a WHERE a.name = b.name)
where b.name in (select a.name from tmp_A a);

Oracle also support n-ordered tuple. So if you want to update all row in a single run, the following command is also valid -

UPDATE tmp_B b
SET (age,name) = (SELECT a.age, a.name FROM tmp_A a WHERE a.name = b.name);

For MS Sql Server the command will be-

update tmp_B
set tmp_B.age=tmp_A.age
from tmp_A,tmp_B where tmp_A.name=tmp_B.name;