merge主要用于两表之间的关联操作
oracle中 merge:
从oracle 9i开始支持merge用法,10g有了完善
create table a (id_ integer,count_ integer);
insert into a values(1,3);
insert into a values(3,6);
create table b (id_ integer,count_ integer);
insert into b values(1,7);
insert into b values(2,4);
MERGE INTO a
USING b
ON (a.id_ = b.id_)
WHEN MATCHED THEN
UPDATE SET count_ = b.count_+a.count_ /* 注意指名count_属于的表 */
WHEN NOT MATCHED THEN
INSERT VALUES (b.id_,b.count_);
commit;
select * from a;
结果:
id_ count_
1 10
3 6
2 4
SQL Server 2008开始支持merge:
有两张结构一致的表:test1,test2
create table test1
(id int,name varchar(20))
go
create table test2
(id int,name varchar(20))
go
insert into test1(id,name)
values(1,'boyi55'),(2,'51cto'),(3,'bbs'),(4,'fengjicai'),(5,'alis')
insert into test2(id,name)
values(1,'boyi'),(2,'51cto')
将test1同步到test2中,没有的数据进行插入,已有数据进行更新 merge test2 t --要更新的目标表
using test1 s --源表
on t.id=s.id --更新条件(即主键)
when matched --如果主键匹配,更新
then update set t.name=s.name
when not matched then insert values(id,name);--目标主未知主键,插入。此语句必须以分号结束
运行以下查询查看更新结果
select a.id,a.name as name_1,b.name as name_2 from test1 as a,test2 as b
where a.id=b.id
id name_1 name_2
----------- -------------------- --------------------
1 boyi55 boyi55
2 51cto 51cto
3 bbs bbs
4 fengjicai fengjicai
5 alis alis