oracle中的replace into
mybaitis foreach批量insert以及配合oracle merge into函数,批量update和insert
oracle中相当于mysql的replace into函数:merge into
- 因为作者使用国产的神通数据库 写法与oracle相同 没办法使用mysql的replace into实现插入
- 使用merge into来代替 不太推荐使用这个 能不用尽量不用吧
使用方法
普通使用
- xml中
<update id="mergestudents" parametertype="com.alibaba.dto.studentdto"> merge into t_student a using ( select #{id} as id, #{name} as name, #{age} as age from dual ) b on ( a.id= b.id ) when matched then update set a.name= b.name, a.age=b.age when not matched then insert( a.id, a.name, a.age ) values( b.id, b.name, b.age ) </update>
加上foreach
<update id="mergestudents" parametertype="com.alibaba.dto.studentdto"> merge into t_student a using ( <foreach collection="stus" item="item" index="index" open="" close="" separator="union all"> select #{item.id,jdbctype=varchar} as id, #{item.name,jdbctype=varchar} as name, #{item.age,jdbctype=varchar} as age from dual </foreach> ) b on ( a.id= b.id ) when matched then update set a.name= b.name, a.age=b.age when not matched then insert( a.id, a.name, a.age ) values( b.id, b.name, b.age ) </update>
弊端:
mybatis会报一个解析不了的语法错误 但不影响实际结果 解决办法暂未发现
com.alibaba.druid.sql.parser.parserexception: syntax error, error in :'merge into
也算mybatis的bug吧 没有update与insert都兼容的标签
用oracle的merge实现mysql的replace into
mysql
mysql有一个replace into的dml语句,类似insert,但是会在insert之前检查表的唯一索引或主键。如果存在,就改为update操作。
这在很多应用中是一个很常用的操作。有了这个replace into ,就可以将一个 select后判断后做update or insert改为一句话,甚是方便。
oracle
oracle9i引入了merge命令,你能够在一个sql语句中对一个表同时执行inserts和upda tes操作. merge命令从一个或多个数据源中选择行来updating或inserting到一个或多个表.在oracle 10g中merge有如下一些改进:
1、update或insert子句是可选的
2、update和insert子句可以加where子句
3、在on条件中使用常量过滤谓词来insert所有的行到目标表中,不需要连接源表和目标表
4、update子句后面可以跟delete子句来去除一些不需要的行
5、源表就是using关键字后面跟的表,目标表就是将要被merge into的表
6、merge into 中所有的update、insert、delete都是针对目标表来操作的。由于merge into已经制定了操作的表,所以update、insert、delete都不需要再显示指出表名
作用:merge into 解决用b表跟新a表数据,如果a表中没有,则把b表的数据插入a表;
语法
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 ! ]
sql demo
如下所示:
merge into qq a using (select '2022' company_no, 'cname' company_name from qq where rownum<2) b on (a.company_no = b.company_no) when matched then update set a.company_name = a.company_name|| 'a' when not matched then insert (a.company_no, a.company_name) values (b.company_no, b.company_name);
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论