Automatically resolve primary key merge conflict
could you please suggest me the way I could automatically resolve primary key conflicts during a merge between Publisher and Subscriber. It seems Sql Server doesn't do it out of the开发者_开发知识库 box :(.
Conflict viewer shows me next message:
A row insert at '_publisher_server_' could not be propagated to '_subscriber_server_'. This failure can be caused by a constraint violation. Violation of PRIMARY KEY constraint 'PK_PartPlan_FD9D7F927172C0B5'. Cannot insert duplicate key in object '_table_name_'.
Thank you.
This isn't an easy solution (since you've presumably already designed your database with auto-incrementing int
keys), but using GUID ("uniqueidentifier") for your primary keys will solve your PK collision problem.
Have you tried WHEN MATCHED THEN
and WHEN NOT MATCHED BY TARGET THEN
to do an UPSERT (conditional UPDATE or INSERT)?
Documentation can be found here.
I'm assuming the primary key represents the same item in both DBs.
The easiest way I have solved this problem using autonumer PK's is to change the autonumber increment from 1 to 10 (or 100, or 1000, whatever is required) then set the seed differently on all the participants.
So, I may start seeds:
DB1 at 1
DB2 at 2
DB3 at 3
...
DBn at n (n < increment)
For example: An increment of 100 will yield PK's for DBs:
DB1: ** 101, 201, 301...
DB2: ** 102, 202, 302...
DB3: ** 103, 203, 303...
No matter how many rows are INSERT
ed they will always have unique PKs because the final digits reflect the particular database.
This method can be adapted as needed for your number of subscribers, they will never collide, and you have the added benefit of knowing the point-of-origin just given your surrogate key.
For existing tables, just reset the PK seeds and intervals by script. It should be very easy to do.
You could use a GUIDE PK but using a GUID can be quite problematic as a primary key, particularly if you don't also remove it from the clustered index. They are larger as well and you may already have code depending on integers.
When you create merge replication, SQL Server automatically creates GUIDs that it uses to track changes, but that doesn't mean they need to be PK's
精彩评论