[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>

 

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值