oracle中的replace into使用
oracle中的replace into
Mybaitis foreach批量insert以及配合oracle merge into函数,批量update和insert
oracle中相当于mysql的replace into函数:merge into
使用方法
普通使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | < 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | < 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表;
语法
1 2 3 4 5 | 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
如下所示:
1 2 3 4 5 6 7 8 9 10 | 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);
|