merge在oracle用以从另一张表中取数据插入到一张表中,如果两张表中记录符合某些条件,则替换,如果不符合则插入。下面的例子是把mergetest中记录更新到newmergetest,如果两张表的id相同,则更新newmergetest,否则插入:
首先建两张测试表:
create table mergetest(id number primary key,name varchar(20));
create table newmergetest(id number primary key,name varchar(20));
往两张表中插入数据:
insert into newmergetest values(1,'first');
insert into newmergetest values(2,'second');
insert into mergetest values(1,'one')
insert into mergetest values(2,'two');
insert into mergetest values(3,'three');
运行更新sql语句:
MERGE INTO newmergetest m
using (select * from mergetest) t
ON (m.id = t.id)
WHEN NOT MATCHED THEN
INSERT VALUES (t.id,t.name)
WHEN MATCHED THEN
UPDATE SET m.name = t.name
执行完后,newmergetest中的记录将和mergetest中的一致。不会因为违反主键约束而更新失败。