首页 > 数据库技术 > 详细

SQLserver 中 merge into 的用法

时间:2021-08-20 09:37:17      阅读:19      评论:0      收藏:0      [点我收藏+]

前言

如何可以高效的把临时表中的数据更新到目标表中呢?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的时候使用,可以大大的提高效率,并且减少锁表的几率。

SQLserver 中 merge into 的用法

原文:https://www.cnblogs.com/ZengJiaLin/p/15161536.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!