Question

I know by default SQL Server replication adds WITH NOCHECK and NOT FOR REPLICATION to the foreign keys after transactional replication. But is there are way, where I can avoid these code changes made by replication. We use a compare tool and these small changes get highlighted. I have an understanding, why they are placed, but some requirements have come up in which I want to have WITH CHECKs constraint at subscriber side as well. I just want to know if somehow we can avoid these few additions and changes to articles scripts both on publisher and subscriber.

The orignal script looks like this:

ALTER TABLE [dbo].[Tablename] WITH CHECK ADD CONSTRAINT [FK__E__06] FOREIGN KEY ([eId]) REFERENCES [dbo].[table] ([Id]) 
GO
ALTER TABLE [dbo].[Tablename] WITH CHECK ADD CONSTRAINT [FK__E_S__05] FOREIGN KEY ([nId]) REFERENCES [dbo].[table] ([Id])
GO

Altered script at subscriber appeared as this:

ALTER TABLE [dbo].[Tablename] WITH NOCHECK ADD CONSTRAINT [FK__E__06] FOREIGN KEY ([eId]) REFERENCES [dbo].[table] ([Id]) NOT FOR REPLICATION
GO
ALTER TABLE [dbo].[Tablename] WITH NOCHECK ADD CONSTRAINT [FK__E_S__05] FOREIGN KEY ([nId]) REFERENCES [dbo].[table] ([Id]) NOT FOR REPLICATION
GO

I want to avoid these changes and in article properties pane, I have seleced True for contraints to be copied at subscriber

Was it helpful?

Solution

I know by default SQL Server replication adds WITH NOCHECK and NOT FOR REPLICATION

Not quite. By default they are CHECK or NOCKECK to match the constraint on the publisher, but set to NOT FOR REPLICATION, so updates from the distribution agent do not fire the constraint.

You can choose

1) Whether or not the constraints are copied in the first place in the article properties, by setting or 0x200 flag (2nd byte, 2nd bit) in the schema_option bitmask in sp_addarticle

0x200 Replicates foreign key constraints. If the referenced table is not part of a publication, all foreign key constraints on a published table are not replicated

2) Whether they are created with the NOT FOR REPLICATION option at the subscriber, by setting or clearing the 0x20000 flag (3rd byte, 2nd bit)

0x20000 Replicates FOREIGN KEY constraints as NOT FOR REPLICATION so that the constraints are not enforced during synchronization.

By default this nibble is 3, as the 0x10000 flag that controls check constraints is also set. So set this nibble to 0x10000 to create FK constraints without the NOT FOR REPLICATION option and to 0x00000 to create both FK constraints and check constraints without the NOT FOR REPLICATION option.

See generally Control Behavior of Triggers and Constraints in Synchronization

Licensed under: CC-BY-SA with attribution
Not affiliated with dba.stackexchange
scroll top