目录
Oracle 中merge into不能更新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')