Automatically resolve primary key merge conflict

限于喜欢 提交于 2019-12-01 23:49:49

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 INSERTed 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!