1. 程式人生 > 其它 >SQLserver 中 merge into 的用法

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