• mybatis+sqlServer 实现insertOrUpdate


    这两天遇到一个头疼的问题,我们系统需要请求第三方数据,第三方收到请求后会生成相应的数据并入库,我们通过定时任务将第三方数据同步到我们数据库。当我们发送请求后第三方会立即返回一个值,我们会根据返回值去数据库更新同步过来的表字段,sql语句执行完了,没有任何错误,在同步表中查看同步的数据都有且where条件完全符合,但是就是没有将指定字段更新掉,最后通过多方对比,发现更新在前,插入在后。在此,贴出最简单的解决方法:

    <insert id="insertOrUpdate">

    if not exists (select 1 from table_name where column_name = XX)
        insert into table_name(id, update_time) values(1, getdate())
    else
        update table_name set update_time = getdate() where id = 1

    </insert>

    先同步或是先更新没有确定,所以如果已存在则更新否则插入

    2019年10月14号更新:

    merge语法:

    MERGE [ TOP ( expression ) [ PERCENT ] ]

    [ INTO ] <target_table> [ WITH ( <merge_hint> ) ] [ [ AS ] table_alias ]

    USING <table_source>

    ON <merge_search_condition>

    [ WHEN MATCHED [ AND <clause_search_condition> ]

    THEN <merge_matched> ] [ ...n ]

    [ WHEN NOT MATCHED [ BY TARGET ] [ AND <clause_search_condition> ]

    THEN <merge_not_matched> ]

    [ WHEN NOT MATCHED BY SOURCE [ AND <clause_search_condition> ]

    THEN <merge_matched> ] [ ...n ]

    [ <output_clause> ] [ OPTION ( <query_hint> [ ,...n ] ) ] ;

    示例:

    merge tb_backlog as target

    using tb_logdb as source

    on target.backlog_id = source.log_id

    --目标表和源表匹配则执行update操作

    when matched then

    update set target.backlog_param = source.log_param

    --目标表中没有,源表中存在则执行insert操作,将源表中存在而目标表不存在的记录插入到目标表中

    when not matched then 

    insert (backlog_id,backlog_name,backlog_url) values(source.log_id,source.log_name,source.log_url)

    --目标表中存在,源表不存在则执行delete操作,删除目标表中的源表不存在的记录

    when not matched by source then 

    delete;

    注意:结尾的分号不可少

  • 相关阅读:
    常用模块汇总
    day 16 常用模块 time 和 datetime(1)
    二分法 函数式 模块
    day 15 模块 (3)
    vue require.context 检索文件夹内文件路径
    Node.js搭建本地服务,读取css/js/img/html等各种格式文件
    Nodejs搭建web服务器
    el-table横向滚动条固定在屏幕最下方显示
    IE浏览器 backspace键使浏览器回退
    vue ElementUI el-input 键盘enter事件 导致刷新表单问题
  • 原文地址:https://www.cnblogs.com/xxjcai/p/11443976.html
Copyright © 2020-2023  润新知