Merge的用法
Merge可以完成以下功能:
1、 兩個表之間數據的更新
2、 進行進銷存更新庫存
3、 進行表之間數據的復制
語法說明:
1、 在語句結束后一定要用分號,否則會提示錯誤。
2、 Merge后為目標表,Using后為數據源表
3、 如果有兩個
When
matched,則必須使用and來限定第一個子句,一個子句必須制定一個update,另一個必須制定delete
4、
When
not matched by target,這個子句處理存在於數據源之中,但不存在目標之中的數據行。
5、
When
not matched等價於
When
not matched by target
6、
When
not mathed by source,這個子句處理,存在於目標中,但是不存在數據表之中的數據行
一、兩個表之間數據的更新
create table test1 (col1 int,col2 varchar(100))
create table test2 (col3 int,col4 varchar(100))
insert into test1
values(1,
'wang'),(2,'trieagle')
insert into test2(col3)
values(1),(2)
merge test2
using test1
on test1.col1=test2.col3
when matched then update set col4=col2;
select * from test2
結果:
col3 col4
1 wang
2 trieagle
二、進行進銷存更新庫存
Trade表為模擬進出庫記錄,正數表示入庫,負數表示出庫
create table stock(id int,qty int)
create table trade(id int ,qty int)
go
insert into stock
values (1,10), (2,20)
insert into trade
values(1,10),(1,-5),(1,20),(2,10),(2,-30),(3,5)
merge stock
using (select id,qty=sum(qty) from trade group by id) K
on stock.id=k.id
when matched and (stock.qty+k.qty)=0 then delete
when matched then update set stock.qty=stock.qty+k.qty
when not matched by target then insert values(k.id,k.qty);
select * from stock
結果:
id qty
1 35
3 5
三、進行表之間數據的復制
drop table test1
drop table test2
create table test1 (col1 int,col2 varchar(100))
create table test2 (col3 int,col4 varchar(100))
insert into test1
values(1,
'wang'),(2,'trieagle')
merge test2
using test1 on test1.col1 =test2.col3
when matched and col2!=col4 then update set col4=col2
when not matched then insert values(col1,col2)
when not matched by source then delete;
select* from test2
結果:
col3 col4
1 wang
2 trieagle
繼續:刪掉test1中的一行,然后增加一行
Delete test1 where col1=1
Insert into test1 values(3,
'wyq')
然后再執行
merge test2
using test1 on test1.col1 =test2.col3
when matched and col2!=col4 then update set col4=col2
when not matched then insert values(col1,col2)
when not matched by source then delete;
結果:
col3 col4
2 trieagle
3 wyq
轉自:http://blog.csdn.net/gongjian0628/article/details/12751761