在更新数据仓库时,经常需要根据源表对Target表进行数据同步,Merge 命令具有数据更新,删除,插入的功能,专门用于数据同步,并将数据的更新输出到表中。在使用Merge命令时,需要注意when not matche子句:

  • when not matched by target :当Target Table不匹配时,数据行不存在于Target Table中,存在于Source Table;
  • when not matched by source:当Source Table不匹配时,数据行不存在于Source Table中,存在于Target Table;
  • 当不指定by子句时,默认值是by target;

1,创建示例数据

use tempdb
go

create table dbo.tar
( 
id int not null,
name varchar(11) not null
)
go
create table dbo.src
(
id int not null,
name varchar(11) not null
)
go
insert into dbo.tar
values(1,'t1'),(2,'t2'),(3,'t3')
insert into dbo.src(id,name)
values(1,'t1'),(2,'s2'),(4,'s4')

create table dbo.dt_merge_output
(
action nvarchar(10) not null,
Deleted_ID int not null,
Deleted_Name nvarchar(11) not null,
Inserted_ID int not null,
Inserted_Name nvarchar(11) not null
)
go
View Code

相关文章: