Oracle 中merge into不能更新on中的字段解决方法

在Oracle中使用merge into更新数据时遇到不能更新on子句中字段的错误,文章详细介绍了这个问题的背景、merge语法基础,通过示例展示了merge的用法,并提供了当遇到'无法更新 ON 子句中引用的列'错误时的解决方案,即把on里的条件移到update后的where子句中。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

目录

Oracle 中merge into不能更新on中的字段解决方法

1.问题描述

2.merge语法简介

3.Merge示例

 4.Merge更新 on中字段问题


Oracle 中merge into不能更新on中的字段解决方法

1.问题描述

应用场景中在更新数据库之前需要判断库中是否有数据,有的话更新没有新增,一般在service中先查询在判断,为解决高并发的问题在Sql中做判断。

2.merge语法简介

merge into target_table a
 
using source_table b
 
on(a.condition1=b.condition1 and a.condition2=b.condition2 ……)  
 
when matched then update set a.field=b.field,....
 
when  not matched then insert into a(field1,field2……)values(value1,value12……)

 target_table 目标表

 source_table  源表 可能是一张表结构不同于a的表,有可能是一张构建相同表结构的临时表,也有可能是我们自己组起来的数据

3.Merge示例

merge into CIF_PERBASEINFO a 

using (select '37*********X' cardnum  from dual ) b

on (a.CARDNUM=b.cardnum ) 

when matched then update set cname='更新' 

when not matched then insert (cardnum,CNAME) values ( '31**********1' ,'新增');

 4.Merge更新 on中字段问题

merge into CIF_PERBASEINFO a 

using (select '37*********X' cardnum  from dual ) b 

on (a.CARDNUM=b.cardnum and a.ISALLCREDIT is  null ) 

when matched then update set cname='客户类型1', ISALLCREDIT='A01' 

when not matched then insert (cardnum,cname,ISALLCREDIT) values ('37*********X', '客户类型2','A02' )

语句执行时报错:无法更新 ON 子句中引用的列: "A"."ISALLCREDIT"

解决方案:on里的条件放到update 之后的where条件里

merge into CIF_PERBASEINFO a
using (select '37*********X' cardnum
       from dual) b
on (a.CARDNUM = b.cardnum )
when matched then
  update
  set cname='客户类型1',
      ISALLCREDIT='A01' where a.ISALLCREDIT is null
when not matched then
  insert (cardnum,cname, ISALLCREDIT)
  values ('37*********X','客户类型2', 'A02')

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值