-- り 襷蟇 螳.
drop table #source
drop table #target
create table #source (id int, gb int)
insert #source values(1, 1)
insert #source values(2, 2)
create table #target(seq int identity(1,1), id int, gb int, bdt date, edt date)
--豐蠍一
declare
@begin_dt date
if not exists (select * from #target)
set @begin_dt = '20000101'
else
set @begin_dt = getdate()
merge #target a
using #source b
on a.id = b.id
and a.gb = b.gb
when matched and a.edt = '99991231' and a.id = b.id then
update set
a.edt = @begin_dt
when not matched by target then
insert(id, gb, bdt, edt)
values(b.id, b.gb, @begin_dt, '99991231')
output $action, inserted.*, deleted.*;
--id=1 gb螳 4襦 覲蟆暑る?
update #source
set gb = 4
where id = 1
/*
select * from #source
id gb
1 4
2 2
*/
declare
@begin_dt2 date
if not exists (select * from #target)
set @begin_dt2 = '20000101'
else
set @begin_dt2 = getdate()
merge #target a
using #source b
on a.id = b.id
and a.gb = b.gb
and a.edt = '99991231'
when not matched by target then
insert(id, gb, bdt, edt)
values(b.id, b.gb, @begin_dt2, '99991231')
when not matched by source and a.edt = '99991231' then
update set
a.edt = @begin_dt2
output $action, inserted.*, deleted.*;
/*
select * from #target
seq id gb bdt edt
1 1 1 2000-01-01 2010-11-05
2 2 2 2000-01-01 9999-12-31
3 1 4 2010-11-05 9999-12-31
*/
--id=1 gb螳 5襦 覲蟆暑る?
update #source
set gb = 5
where id = 1
declare
@begin_dt3 date
if not exists (select * from #target)
set @begin_dt3 = '20000101'
else
set @begin_dt3 = getdate()
merge #target a --襷 minimal logging 螻 苦朱.. with (TABLOCK) a 螳 企 曙 ′譴.
using #source b
on a.id = b.id
and a.gb = b.gb
and a.edt = '99991231'
when not matched by target then
insert(id, gb, bdt, edt)
values(b.id, b.gb, @begin_dt3, '99991231')
when not matched by source and a.edt = '99991231' then
update set
a.edt = @begin_dt3
output $action, inserted.*, deleted.*;
/*
select * from #target
seq id gb bdt edt
1 1 1 2000-01-01 2010-11-05
2 2 2 2000-01-01 9999-12-31
3 1 4 2010-11-05 2010-11-05
4 1 5 2010-11-05 9999-12-31
*/