zoukankan      html  css  js  c++  java
  • 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 的值一致

    不积跬步无以至千里
  • 相关阅读:
    前端开发——HTML学习笔记
    前端开发——HTML学习笔记
    前端开发——HTML学习笔记
    日记2018/1/4
    物联网概念
    安卓常见英文缩写的全拼
    快速排序和计数排序API
    Hash表API
    栈/队列API(push和pop)
    链表API实现(插入,删除,查找)
  • 原文地址:https://www.cnblogs.com/jinxiuze/p/8241462.html
Copyright © 2011-2022 走看看