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;                --删除目标表中存在,源表中不存在的数据

  • 相关阅读:
    mysql 数据库字符集问题
    适配器模式
    thinkphp学习笔记
    StarDict
    dereferencing pointer to incomplete type
    转载的一篇 关于git的
    策略模式
    让你的Ubuntu看的更顺眼些
    vim 配置
    .NET WEB SERVICE 学习记录
  • 原文地址:https://www.cnblogs.com/guozhaoxin/p/14395174.html
Copyright © 2011-2022 走看看