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的時候使用,可以大大的提高效率,並且減少鎖表的幾率。


免責聲明!

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



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