有两张结构一致的表: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
更多SQL内容来自木庄网络博客