Oracle merge into 的用法

我们平时在操作数据库的时候有时候批量插入数据会面临一个问题就是:

数据如果不存在则执行插入操作;

数据如果存在则执行更新操作;

在mysql数据库中提供了ON DUPLICATE KEY UPDATE这种操作方式在oracle 中也提供了类似的方式:merger into

merger的语法:

MERGE INTO [your table-name] [rename your table here] 
USING ( [write your query here] )[rename your query-sql and using just like a table] 
ON ([conditional expression here] AND [...]...) 
WHEN MATHED THEN [here you can execute some update sql or something else ] 
WHEN NOT MATHED THEN [execute something else here ! ] 

使用例子:

merge into order_info o
using (select * from userinfo u where u.u_name = 'teache1') t
on (o.o_u_id = t.u_id)
when matched then
  update set o.updatetime = sysdate
when not matched then
  insert
    (o.o_id, o.o_name, o.o_u_id, o.addtime)
  values
    (seq_orderinfo.nextval, t.u_name, t.u_id, sysdate);

Merge Into的是从using 搜出来的结果逐条与on条件匹配,然后决定是update还是Insert。 当USING后面的sql没有查询到数据的时候,Merge Into语句是不会执行update和Insert操作的。所以要想让Merge Into正常运行,要保证USING 后面的SELECT有数据,个人喜欢使用DUAL表作为USING后的表,方便自己控制。

如果要传参数可以using中写select #{param} param from dual 这样在on 中写a.param=b.a.param;


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值