zoukankan      html  css  js  c++  java
  • Sqlserver merge(Transact-SQL)用法

    官方文档解释:
       根据与源表联接的结果,对目标表运行插入、更新或删除操作。
      例如:根据与另一个表的区别,在一个表中插入、更新或删除行,从而同步两个表

    性能提示:
      当两个表具有匹配特性的复杂混合时,针对merge语介绍的条件行为的效果最佳。
      例如,插入不存在的行,或更新匹配的行。
      仅根据另一个表的行更新一个表时,通过基本的INSERT、UPDATE、DELETE语句提升性能和可伸缩性。

    用法以下代码为例:

    merge NovoNordisk_DW.dbo.Fact_EXNNSales_StockDay stock 
            using #tempTable temp
            on stock.[LB_Version]= temp.[LB_Version]
            and stock.[LB_Product]=temp.LB_Product and stock.[LB_Year]=temp.[LB_Year] and stock.[LB_Month]=temp.[LB_Month]
            when matched 
                        then update set
                        stock.[LB_StockDay]=temp.LB_StockDay
            WHEN NOT MATCHED BY TARGET 
                        then insert
                              values(
                              temp.[LB_Version]
                              ,temp.[LB_Product]
                              ,temp.[LB_Year]
                              ,temp.[LB_Month]
                              ,temp.[LB_StockDay]
                              ,temp.[StatsDate]
                              ,temp.[UpdatedDate]
                                )
            when not matched by source
                        then delete;

    关键字剖析:

    merge 目标表表名 t1             --将数据最终merge到目标表
    using 源表表名 t2                  --目标表与源表联接
    on t1.xx=t2.xx and t1.aa=t2.aa          --关联匹配的条件
    when matched                 --如果关联匹配的条件匹配成功
      then update set t1.字段=t2.字段      --将源表中的其他字段更新至目标表
    when not matched by target           --如果匹配不成功(target目标表没有这条记录,source源表中有,即source中数据应插入到target目标表)
      then insert values(t2.字段1,t2.字段2)    --将源表中字段插入到目标表
    when not matched by source         --如果匹配不成功(source源表没有这条记录,target目标表中有,即根据具体需求去决定是否删除)
      then delete;                --删除目标表中存在,源表中不存在的数据

  • 相关阅读:
    二叉树的递归遍历框架:
    springmvc 有哪些优点呢?
    springmvc 和 struts2 有哪些区别?
    三层架构 和 MVC 设计模式有哪些区别呢?
    软件测试各个阶段通常完成什么工作?各个阶段的结果文件是什么?包括什么内容?
    软件测试的策略是什么?
    软件产品质量特性是什么?
    软件配置管理的作用?软件配置包括什么?
    什么是软件测试?软件测试的目的与原则
    软件生存周期及其模型是什么?
  • 原文地址:https://www.cnblogs.com/guozhaoxin/p/14395174.html
Copyright © 2011-2022 走看看