MERGE INTO的使用

MERGE INTO用法:

meger into主要用在修改和增加操作中

大致意思是:判断一个条件,如果满足执行update,不满足执行insert

<update id="updateXxh" parameterType="java.util.Map" >
    MERGE INTO table
    USING dual ON (XXHID=#{xxhid})
    WHEN MATCHED THEN
    update set
    BT = #{bt}
    <if test="nd != null and nd != ''">,ND = #{nd}</if>
    <if test="lc != null and lc != ''">,LC = #{lc}</if>
    <if test="xxhnr != null and xxhnr != ''">,XXHNR = #{xxhnr}</if>
    <if test="operatorid != null and operatorid != ''"> ,OPERATORID = #{operatorid}</if>
    <if test="operator != null and operator != ''"> ,OPERATOR = #{operator}</if>
    <if test="status != null and status != ''"> ,STATUS = #{status}</if>
    where XXHID=#{xxhid}
    WHEN NOT MATCHED THEN
    insert
    (
        XXHID
        <if test="bt != null and bt != ''">,BT </if>
        <if test="nd != null and nd != ''">,ND </if>
        <if test="lc != null and lc != ''">,LC </if>
        <if test="xxhnr != null and xxhnr != ''">,XXHNR </if>
        <if test="operatorid != null and operatorid != ''">,OPERATORID </if>
        <if test="operator != null and operator != ''">,OPERATOR </if>
        <if test="status != null and status != ''">,STATUS </if>
    )
    values(
        #{xxhid}
        <if test="bt != null and bt != ''">,#{bt}</if>
        <if test="nd != null and nd != ''">,#{nd}</if>
        <if test="lc != null and lc != ''">,#{lc}</if>
        <if test="xxhnr != null and xxhnr != ''">,#{xxhnr}</if>
        <if test="operatorid != null and operatorid != ''">,#{operatorid}</if>
        <if test="operator != null and operator != ''">,#{operator}</if>
        <if test="status != null and status != ''">,#{status}</if>
    )

</update>

理解

​ 调用的时候会传入一个Map,这个map里面有一个键值对(键的值是:xxhid)。

​ 程序执行到sql的时候,会把这个xxhid从map里面取出来,自动加上单引号拼接进去,执行sql

​ on后面的条件是查询的是table表中是否有xxhid这个值的XXHID键,如果有那就执行下面的update,

如果没有就执行insert操作。

注意:insert后面没有into!!!切记!

平常,我们写代码还可以在Java代码里面进行判断,是执行更新还是插入,但看到同事们的Java代码都是简简单单的调用,我就起了疑,所以学习了一下。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值