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;

3 comments:

SHISHIR said...

Very supportive information.


update TBL_1 a
set(field_1,field_2) = (select field_1,field_2 from TBL_2 b where a.field_3 = b.field_4)
where a.field_3 in (select b.field_4 from TBL_2 b);

Sadique said...
This comment has been removed by the author.
RIYAD said...

merge can also do that

MERGE INTO tbl1
USING tbl2 ON (tbl1.field3=tbl2.field4)
WHEN MATCHED THEN UPDATE SET
tbl1.f1=tbl2.f_1,tbl1.f2=tbl2.f_2