Oracle 中 merge into 的用法


Oracle 中 merge into 的用法

merge into 的用法

對一張表,在不同的條件下實現不同的操作(update/insert),在 oracle 中可以用 merge into
語法:

MERGE INTO table_name alias1 
USING (table|view|sub_query) alias2
 (join condition) 
WHEN MATCHED THEN 
UPDATE table_name 
SET col1 = col_val1, 
       col2 = col_val2 
WHEN NOT MATCHED THEN 
INSERT (column_list) VALUES (column_values);
  • 要對表中某幾條記錄進行判斷並操作,代碼實現如下:

    --  user_table 表中,如果存在 user_skey = 99999 的記錄,則修改該記錄的 last_name 字段, 否則插入一條新紀錄 
        merge into user_table t1 using (select 99999 as user_skey2, 9999 as user_id2 from dual) t2 on  (t1.user_skey = t2.user_skey2) 
    when matched then 
         update  set t1.last_name = '寶強' 
    when not matched then  
         insert  (t1.user_skey , t1.user_id, last_name, first_name, ba_no , dept_id) values (1111,222, '俊傑', '林', 111 ,10)
    

    注:update 和 insert 的記錄總和與 using 后面的集合中的元素個數一致

  • 對表中全部記錄進行操作,代碼實現如下:

     -- user_table 表中, 如果存在 user_skey = 11111 的記錄,則修改所有記錄的 last_name 字段,否則插入一條新的記錄 
         merge into user_table t1 using dual  on ((select count(*) from user_table where user_skey = 11111) > 0)
     when matched then
          update set t1.last_name = '傑倫'
     when not matched then
           insert  (t1.user_skey , t1.user_id, last_name, first_name, ba_no , dept_id) values (1112,222, '俊傑', '林', 111 ,10)
    

    注:update 的記錄條數與 count 的值一致


免責聲明!

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



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