[Oracle]将多条update语句合并为一条
说明:
1.Oracle版本 11g
2.mybatis版本 3.2.3
场景
批量修改数据,但where条件不一样。
举例
表名 tableName
要求将字段A的值为1的数据修改其字段B的值为“B1”;将字段A的值为2的数据修改其字段B的值为“B2”;将字段A的值为3的数据修改其字段B的值为“B3”
实现
一、对此可以写3条update语句来实现需求
update tableName set B = 'B1' where A = '1'
update tableName set B = 'B2' where A = '2'
update tableName set B = 'B3' where A = '3'
二、对多条update语句进行合并
update tableName set B = (case A
when '1' then 'B1'
when '2' then 'B2'
when '3' then 'B3'
end)
where A in ('1','2','3')
三、mybatis中的Mapper编写实现
1.定义入参List<T> list = new ArrayList<>()
2.list中添加值(伪代码)
t1.setA("1");t1.setB("B1");list.add(t1);
t1.setA("2");t1.setB("B2");list.add(t2);
t1.setA("3");t1.setB("B3");list.add(t3);
3.mapper中语句如下:
<update id="updateBatch">
UPDATE tableName
SET
B = (CASE A
<foreach collection="list" index="index" item="item"
open=" " separator=" " close=" ">
WHEN \#\{item.a\} THEN
\#\{item.b\}
</foreach>
END)
where A in
<foreach collection="list" index="index" item="item"
open="(" separator="," close=")">
\#\{item.a\}
</foreach>
</update>
还没有评论,来说两句吧...