Sql 2008的merge关键字

测试数据

/*目标表和源表*/
declare @target table(id int, de varchar(50))
declare @source table(id int, de varchar(50))
insert into @source values (1,'源1'),(2,'源2'),(3,'源3'),(4,'源4')
insert into @target values 
(1,'在源表里面有1'),(2,'在源表里面有2'),(5,'在源表里面没有5'),(6,'在源表里面没有6')
select * from @target

image

代码一

merge into @target as T
using @source as S on T.id=S.id
when matched then update set T.de=S.de
;
select * from @target

两张表通过id匹配. 如果符合. 则把目标表的de改为源表的de得到数据如image. 红圈两列完成了 更改

代码二.

merge into @target as T
using @source as S on T.id=S.id

when matched        then update set T.de=S.de
when not matched    then insert values(S.id,S.de)        --如果目标表里面没有源表的数据
/*when not matched by source
--                    then delete                            
--如果target里面有, 但是源表没有的就删除. 有点类似于inner join的笛卡尔乘积, 
--左边表里面存着记录, 但是右边表没有. 还是删除掉
*/
output $Action as actiontype,deleted.*,inserted.*
;
select * from @target

同样是通过id匹配. 如果符合. 那么更新, 不符合那么插入.

output是输出. $action是表示这次操作的类型. (insert或者update还有delete). 操作类似于触发器. 能够访问到deleted.*表和inserted.*表的东西.

因此输出

image  . 目标表的,1,2 从image改成imageimage, 因为3,4在目标表里没有.

代码三.  去掉代码二的注释. 会得到什么呢? 就是删除掉source里面没有, target里面有的记录.

image这两条记录在源表里面木有. 所以要删除.

image执行结果.

扩展: 如何在Merge之后删除已经Merge过去的数据.

http://stackoverflow.com/questions/7331725/how-to-delete-from-source-using-merge-command-in-sql-server-2008

本人在长沙, 有工作可以加我QQ4658276
原文地址:https://www.cnblogs.com/jianjialin/p/2413573.html