SQLserver 中 merge into 的用法


目的

merge into高效的把臨時表中的數據更新到目標表中。

merge into 語法

語法如下:

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

merge into 使用案例

創建目標表和源表

腳本如下:

CREATE TABLE UserInfo
(
Id uniqueidentifier not null primary key,
LoginName varchar(255) not null,
UserPwd varchar(255) not null CHECK ((len([UserPwd])>=(6)) and (len([UserPwd])<=(64))),
Name varchar(255) not null,
Phone varchar(255) not null,
)

CREATE TABLE UserInfoBase
(
Id uniqueidentifier not null primary key,
LoginName varchar(255) not null,
UserPwd varchar(255) not null CHECK ((len([UserPwd])>=(6)) and (len([UserPwd])<=(64))),
Name varchar(255) not null,
Phone varchar(255) not null,
)

insert into UserInfo(Id, LoginName, UserPwd, Name, Phone)values(LOWER(NEWID()),'admin','123456','管理員','18600000000'),
(LOWER(NEWID()),'admin1','123456','管理員1','18600000000');

使用merge into

腳本如下:

merge into UserInfo as a
using UserInfoBase as b on b.ID=b.ID
when matched       --更新 目標表中有ID,則更新
then update set a.[LoginName]=b.[LoginName], a.[UserPwd]=b.[UserPwd],a.[Name]=b.[Name],a.[Phone]=b.[Phone]
when not matched   --添加 目標表中沒有ID,在原表中有,則插入相關數據
then insert values (b.[Id],b.[LoginName],b.[UserPwd],b.[Name],b.[Phone])
when not matched by source --目標表存在,源表不存在,則刪除
then delete;

總結

一般用於數據拷貝,批量執行insert和update的時候使用,可以大大的提高效率。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM