Loading

SQLserver 中 merge into 的用法

前言

如何可以高效的把临时表中的数据更新到目标表中呢?merge into可以帮你完美解决。

merge into 语法

语法如下:

merge into 目标表 a
using 源表 b
on a.条件字段1=b.条件字段1 and a.条件字段2=b.条件字段2  ...
when matched update set a.字段1=b.字段1,
						a.字段2=b.字段2
when not matched insert values (b.字段1,b.字段2)
when not matched by source 
then delete 

merge into 使用

创建目标表和源表

脚本如下:

create table targetTable(ID INT primary key identity(1,1),[name] varchar(50),age int)
create table sourceTable(ID INT primary key identity(1,1),[name] varchar(50),age int)
insert into targetTable([name],age) values('大卫',40)

使用merge into

脚本如下:

merge into targetTable as t
using sourceTable as S on t.ID=s.ID
when matched       --更新 目标表中有ID,则更新
then update set t.[name]=S.[name]
when not matched   --添加 目标表中没有ID,在原表中有,则插入相关数据
then insert values (s.[name],s.age)
when not matched by source --目标表存在,源表不存在,则删除
then delete;

总结

建议在需要批量执行UPDATE的时候使用,可以大大的提高效率,并且减少锁表的几率。

posted @ 2021-08-20 08:45  我是小柒  阅读(819)  评论(0编辑  收藏  举报