在细节上,体现编程的修养。每一位大师,master,其基础必定夯实。废话不多说,直接上干货,Merge子句用于对两个数据表执行数据同步,On子句指定匹配(when matched)条件,When子句指定额外的过滤条件和数据更新逻辑。源表(Source Table)和靶表(Targe Table)的数据行能够匹配成功,这意味着on子句和when match条件都被满足,进入到when matched子句定义的更新代码中,执行数据同步操作;如果不满足on子句,那么必须深入理解不匹配(when not matched)子句的条件,否则,很容易出错。首先查看MSDN对On子句的定义:

ON <merge_search_condition>  target_table to determine where they match.

It is important to specify only the columns from the target table that are used for matching purposes. That is, specify columns from the target table that are compared to the corresponding column of the source table. Do not attempt to improve query performance by filtering out rows in the target table in the ON clause, such as by specifying AND NOT target_table.column_x = value. Doing so may return unexpected and incorrect results.

在开始测试when not matched子句的陷进之前,使用以下脚本创建示例数据:

create table dbo.dt_source
(
    ID int,
    Code int
)
go
create table dbo.dt_target
(
    ID int,
    Code int
)
go
insert into dbo.dt_source
(
ID,
Code
)
values(1,1),(2,1),(3,2),(4,2),(5,0)
GO
insert into dbo.dt_target
(
ID,
Code
)
values(1,1),(6,4)
GO
View Code

相关文章:

  • 2021-10-26
  • 2022-12-23
  • 2021-11-18
  • 2022-12-23
  • 2021-11-06
  • 2021-11-02
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-09-04
  • 2022-12-23
  • 2021-10-22
  • 2021-11-28
  • 2022-12-23
  • 2022-12-23
  • 2021-06-02
相关资源
相似解决方案