[Oracle]将多条update语句合并为一条

女爷i 2021-10-15 01:33 974阅读 0赞

说明:

  1. 1.Oracle版本 11g
  2. 2.mybatis版本 3.2.3

场景

  1. 批量修改数据,但where条件不一样。

举例

  1. 表名 tableName
  2. 要求将字段A的值为1的数据修改其字段B的值为“B1”;将字段A的值为2的数据修改其字段B的值为“B2”;将字段A的值为3的数据修改其字段B的值为“B3

实现

一、对此可以写3条update语句来实现需求

  1. update tableName set B = 'B1' where A = '1'
  2. update tableName set B = 'B2' where A = '2'
  3. update tableName set B = 'B3' where A = '3'

二、对多条update语句进行合并

  1. update tableName set B = (case A
  2. when '1' then 'B1'
  3. when '2' then 'B2'
  4. when '3' then 'B3'
  5. end)
  6. where A in ('1','2','3')

三、mybatis中的Mapper编写实现

  1. 1.定义入参List<T> list = new ArrayList<>()
  2. 2.list中添加值(伪代码)
  3. t1.setA("1");t1.setB("B1");list.add(t1);
  4. t1.setA("2");t1.setB("B2");list.add(t2);
  5. t1.setA("3");t1.setB("B3");list.add(t3);
  6. 3.mapper中语句如下:
  7. <update id="updateBatch">
  8. UPDATE tableName
  9. SET
  10. B = (CASE A
  11. <foreach collection="list" index="index" item="item"
  12. open=" " separator=" " close=" ">
  13. WHEN \#\{item.a\} THEN
  14. \#\{item.b\}
  15. </foreach>
  16. END)
  17. where A in
  18. <foreach collection="list" index="index" item="item"
  19. open="(" separator="," close=")">
  20. \#\{item.a\}
  21. </foreach>
  22. </update>

发表评论

表情:
评论列表 (有 0 条评论,974人围观)

还没有评论,来说两句吧...

相关阅读