我们平时在操作数据库的时候有时候批量插入数据会面临一个问题就是:
数据如果不存在则执行插入操作;
数据如果存在则执行更新操作;
在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;