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 的值一致

posted @   别离的岁月  阅读(7202)  评论(0编辑  收藏  举报
编辑推荐:
· DeepSeek 解答了困扰我五年的技术问题
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· 用 C# 插值字符串处理器写一个 sscanf
· Java 中堆内存和栈内存上的数据分布和特点
· 开发中对象命名的一点思考
阅读排行:
· 为什么说在企业级应用开发中,后端往往是效率杀手?
· DeepSeek 解答了困扰我五年的技术问题。时代确实变了!
· 本地部署DeepSeek后,没有好看的交互界面怎么行!
· 趁着过年的时候手搓了一个低代码框架
· 推荐一个DeepSeek 大模型的免费 API 项目!兼容OpenAI接口!
点击右上角即可分享
微信分享提示