merge into函数作用为:

    • 当存在该条数据时,执行更新操作
    • 当不存在该条数据时,执行新增操作

      语法: merge into [target-table] A using [source-table sql] B

      1. on ([conditional expression] and [...]...)

      when matched then — 当on中的条件匹配时

      1. [update sql] -- 执行操作 更新或删除等

      when not matched then — 当on中的条件不匹配时

      1. [insert sql] -- 执行操作 新增等

      该语法用于:
      判断B表和A表是否满足ON中条件,如果满足则用B表去更新A表(或其他操作), 如果不满足,则将B表数据插入A表但是有很多可选项(或其他操作)。 其中:B表是作为条件来源或数据对比的作用,实际操作,一般是针对A表.

    示例:
    当合同表A存在合同号为'$contno$'的记录时,执行更新金额为'$amt$';当合同表不存在合同号为'$contno$'的记录时,执行新增一条记录。

    1. merge into CC_CONTRACTINFO A
    2. using (SELECT '$contno$' AS CONTRACTNO FROM DUAL) B
    3. on(A.CONTRACTNO = B.CONTRACTNO)
    4. when matched then
    5. update set A.amt = '$amt$'
    6. when not matched then
    7. insert (CONTRACTNO,AMT) VALUES('$contno$','$amt$');

    注意:我们可以同时使用when matched thenwhen not matched then,也可以仅使用其中一个情况进行更新表数据操作。