MERGE語法詳解


merge語法是根據源表對目標表進行匹配查詢,匹配成功時更新,不成功時插入。

其基本語法規則是

merge into 目標表 a

using 源表 b

on(a.條件字段1=b.條件字段1 and a.條件字段2=b.條件字段2 ……)  

when matched then update set a.更新字段=b.字段

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……)

變種寫法①,只更新:

merge into 目標表 a

using 源表 b

on(a.條件字段1=b.條件字段1 and a.條件字段2=b.條件字段2 ……)  

when matched then update set a.更新字段=b.字段,a.更新字段2=b.字段2……

變種寫法②,只插入:

merge into 目標表 a

using 源表 b

on(a.條件字段1=b.條件字段1 and a.條件字段2=b.條件字段2 ……)  

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……)

注:條件字段不可更新

對於Oracle來說,merge是9i新增的語法,在10g進行了一些增強,如下:

測試環境:Oracle Database 11g Enterprise Edition Release 11.2.0.1.0

①條件操作:

merge into 目標表 a

using 源表 b

on(a.條件字段1=b.條件字段1 and a.條件字段2=b.條件字段2 ……)  

when matched then update set a.更新字段=b.字段  where 限制條件

when  not macthed then insert into a(字段1,字段2……)values(值1,值2……) where 限制條件

舉例:

merge into test_merge a
using test b
on(a.no=b.no)
when matched then update set a.no2=b.no2 where a.no<>1
when not matched then insert values(b.no,b.no2)  where a.no<>100

當然也支持變種①②的寫法

②刪除操作

merge into 目標表 a

using 源表 b

on(a.條件字段1=b.條件字段1 and a.條件字段2=b.條件字段2 ……)  

when matched then update set a.更新字段=b.字段

delete where b.字段=xxx

舉例:

merge into test_merge a
using test b
on(a.no=b.no)
when matched then update set a.no2=b.no2 where a.no<>1
delete
where b.no=14

備注:刪除動作針對的也是目標表,並且必須在語句最后

基本上merge的用法就是以上這些,建議平常可以多用,比單獨的update+insert的方式效率要更高,尤其是on條件下有唯一索引的時候,效率更高

 

 




免責聲明!

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



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