欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

SQL中Merge用法詳解

 更新時(shí)間:2015年09月16日 16:01:34   作者:wengyupeng  
Merge關(guān)鍵字是一個(gè)神奇的DML關(guān)鍵字。它在SQL Server 2008被引入,它能將Insert,Update,Delete簡(jiǎn)單的并為一句,本文給大家重點(diǎn)介紹sql中merge用法,需要的朋友一起了解下吧

MERGE語(yǔ)句是SQL語(yǔ)句的一種。在SQL Server、Oracle數(shù)據(jù)庫(kù)中可用,MySQL、PostgreSQL中不可用。MERGE是Oracle9i新增的語(yǔ)法,用來合并UPDATE和INSERT語(yǔ)句。通過MERGE語(yǔ)句,根據(jù)一張表(原數(shù)據(jù)表,source table)或子查詢的連接條件對(duì)另外一張(目標(biāo)表,target table)表進(jìn)行查詢,連接條件匹配上的進(jìn)行UPDATE,無法匹配的執(zhí)行INSERT。這個(gè)語(yǔ)法僅需要一次全表掃描就完成了全部工作,執(zhí)行效率要高于INSERT+UPDATE。

merge主要用于兩表之間的關(guān)聯(lián)操作

oracle中 merge:

從oracle 9i開始支持merge用法,10g有了完善

create table a (id_ integer,count_ integer);
insert into a values(1,3);
insert into a values(3,6);
create table b (id_ integer,count_ integer);
insert into b values(1,7);
insert into b values(2,4);
MERGE INTO a
 USING b
 ON (a.id_ = b.id_)
WHEN MATCHED THEN
 UPDATE SET count_ = b.count_+a.count_ /* 注意指名count_屬于的表 */
WHEN NOT MATCHED THEN
 INSERT VALUES (b.id_,b.count_);
commit;
select * from a;

結(jié)果:

    id_   count_
    1        10
    3          6
    2          4

SQL Server 2008開始支持merge:

有兩張結(jié)構(gòu)一致的表:test1,test2

create table test1 
(id int,name varchar(20)) 
go 
create table test2 
(id int,name varchar(20)) 
go 
insert into test1(id,name) 
values(1,'boyi55'),(2,'51cto'),(3,'bbs'),(4,'fengjicai'),(5,'alis') 
insert into test2(id,name) 
values(1,'boyi'),(2,'51cto')

將test1同步到test2中,沒有的數(shù)據(jù)進(jìn)行插入,已有數(shù)據(jù)進(jìn)行更新

merge test2 t --要更新的目標(biāo)表 
using test1 s --源表 
on t.id=s.id --更新條件(即主鍵) 
when matched --如果主鍵匹配,更新 
then update set t.name=s.name 
when not matched then insert values(id,name);--目標(biāo)主未知主鍵,插入。此語(yǔ)句必須以分號(hào)結(jié)束

運(yùn)行以下查詢查看更新結(jié)果

select a.id,a.name as name_1,b.name as name_2 from test1 as a,test2 as b 
where a.id=b.id

id          name_1               name_2
----------- -------------------- --------------------
1           boyi55               boyi55
2           51cto                51cto
3           bbs                  bbs
4           fengjicai            fengjicai
5           alis                 alis

相關(guān)文章

最新評(píng)論