tsql - How implement correctly MERGE for tables? Incorrect CDC result -
once of day 1 local sql server doing synchronization linked server. following query using merge:
merge [targetdb].[dbo].[targettable] target using (select * [remoteserver].[sourcedb].[dbo].[testtable]) source on (target.[id] = source.[id]) when matched update set target.[id] = source.[id], target.[testfieldstring] = source.[testfieldstring], target.[testfieldint] = source.[testfieldint] when not matched target insert (id, testfieldstring, testfieldint) values (id, source.testfieldstring, source.testfieldint);
also on target server works cdc
(change data capture). looks @ cdc
statistic found transaction on update not register in cdc
. following query statistics capture:
select ch.*, ch.__$seqval, case ch.__$operation when 1 'delete' when 2 'insert' when 3 'prev val' else 'new val' end operation, map.tran_begin_time, map.tran_end_time [cdc].[dbo_testtable_ct] ch join [cdc].[lsn_time_mapping] map on ch.[__$start_lsn] = map.start_lsn order ch.__$start_lsn, ch.__$seqval
after several tests became clear. happens tables contains primary key. if source table pk contains changes merge query doing delete
, doing insert
each row.
- result of first merge in 1 row. target table empty before operation.
- update for
testfieldstring
in source table , result second merge in 2 , 3 rows. - inserting new record in source table , executing merge. result third merge in 4,5,6 rows.
it strange. waiting prev val
, new val
in operation column. script creating table looks folowing:
create table [dbo].[testtable]( [id] [uniqueidentifier] not null primary key, [testfieldstring] [varchar](50) null, [testfieldint] [int] null ) on [primary] go
folowing cdc result similar table without primary key.
- result of first merge in 1 row. target table empty before operation.
- updating for
testfieldstring
in source table , merging. result in 2 , 3 rows. - inserting new record in source table , merging. result in 4 row.
it correct cdc
result following table:
create table [dbo].[testtable]( [id] [uniqueidentifier], [testfieldstring] [varchar](50) null, [testfieldint] [int] null ) on [primary] go
i read on msd merge don't find description issue.
how fix , wrong? maybe bug or feature of merge
clause or cdc
functionality? issue, functionality i'm developing, critical issue.
also, before merge attempted disabled constraints in table got error cdc locked constraints. maybe there possible mark constraints (in case primary key) before merge , after correct cdc result?
also, before merge runing folowing sp:
exec sp_msforeachtable @command1='alter table ? nocheck constraint all'
and after merge folowing:
exec sp_msforeachtable @command1='alter table ? check constraint all'
Comments
Post a Comment