SqlServer中的merge into

今天学到了sqlserver中的merge into,在这里记录一下自己的学习过程。

首先我们要准备两个表。

SqlServer中的merge into

SqlServer中的merge into

随后贴出来的merge into代码,它会在插入时做检测,若表中已存在数据,会用新数据做更新,若表中不存在数据,会把新数据插入表中。

merge into [Test].[dbo].[merge_target] as t #merge into后的表被当做目标表
using [Test].[dbo].[merge_source] as s #using后的表被当做源表
on t.name=s.name #on后写的是两张表的链接条件
when matched #如果数据匹配上
then update set t.id=s.id #用source表的id去更新target表的id
when not matched by target #如果没有匹配上,也就是target表里没有source表的数据
then insert (name,age,id) values (s.name,s.age,s.id) #把数据插入到target表
when not matched by source #如果target表中存在source表没有的数据
then delete #则删除target表的数据
; #一定要带上这个分号,不然会报错
下面这是运行结果

SqlServer中的merge into

现在对source表做一下修改,让表里有重复的数据。
SqlServer中的merge into
之后再运行merge into语句,会报错,报错信息如下:
MERGE语句多次尝试更新或删除相同的行。当目标行匹配多个源行时,就会发生这种情况。合并语句不能多次更新/删除目标表的同一行。细化ON子句以确保目标行最多匹配一个源行,或者使用GROUP BY子句对源行进行分组。

source表里不能有重复的数据。也就是作为on条件的name列在source表里不能重复。