merge 目标表
using 源表
on 匹配条件
when matched then
语句
when not matched then
语句;
其中最后语句分号不可以省略,且源表既可以是一个表也可以是一个子查询语句
when not matched by target
表示目标表不匹配,by target是默认的,所以上面我们直接使用when not matched then
when not matched by source
表示源表不匹配,即目标表中存在,源表中不存在的情况。
主要用法:
merge无法多次更新同一行,也无法更新和删除同一行
当源表和目标表不匹配时:
若数据是源表有目标表没有,则进行插入操作
若数据是源表没有而目标表有,则进行更新或者删除数据操作
当源表和目标表匹配时:
进行更新操作或者删除操作
when matched 这个子句可以有两个,当有两个时,第一个子句必须是when matched and condition且两个matched子句只会执行一个,且两个子句必须
是一个update和一个delete操作
when not matched by source和上面类似
merge icr_codemap_bak as a
using icr_codemap as b
on a.colname = b.colname and a.ctcode = b.ctcode
when matched and b.pbcode <> a.pbcode
then update set a.pbcode = b.pbcode
when not matched
then insert values(b.colname,b.ctcode,b.pbcode,b.note)
;
可以比对字段不一致进行更新
https://technet.microsoft.com/zh-cn/library/bb510625.aspx 这个是msdn的网址
在 merge matched 操作中,只能允许执行 update 或者 delete 语句。
在 merge not matched 操作中,只允许执行 insert 语句。
一个 merge 语句中出现的 matched 操作,只能出现一次 update 或者 delete 语句,否则就会出现下面的错误 - an action of type 'when matched' cannot appear more than once in a 'update' clause of a merge statement.
merge 语句最后必须包含分号,以 ; 结束。
以上就是sqlserver之merge函数用法_mysql的内容。