Ok, I know “SQL Server Replication Error 3726″ isn’t the most imaginative of headlines for a blog article. What little I know about SEO tells me that titles carry more weight when the search engines do their crawls. So, I had to make the decision that this particular title may not actually bring sexy back. I can live with that.
Error 3726: “Could not drop object ‘myTable’ because it is referenced by a FOREIGN KEY constraint.” This is thrown predominantly upon the initial setup of a replication publication. When the snapshot agent is run, one of the first things that is done is the engine verifying whether the articles already exist at the subscriber. If so, one has a choice of either dropping the article entirely (schema included), just deleting the data (closer to a TRUNCATE than a delete because I’m fairly sure it’s not logged), filter based on predetermined criteria, or simply doing nothing. Whichever of the options you choose; if an article you wish to publish has a foreign key constraint that ties it to an object on the publisher that is not published as well, then this error will occur.
Fair enough, but what options do we have for resolving the error? Several actually. The easiest is to simply add the related table to the list of published articles and rerun the snapshot agent. This time around, the agent will recognize both related tables are being published and proceed as expected.
If for some reason you don’t have the flexibility to be able to alter the article list, then your best bet would be to drop and re-add the constraint. This can be done easily with the traditional ALTER TABLE/DROP CONSTRAINT & ALTER TABLE/ADD CONSTRAINT syntax (link) in all versions. Here is an excellent article on dropping and creating FK constraints by Pinal Dave (link). As well, if you’re creating the publication (transactional or snapshot) using sp_addpublication, then there is an optional “@pre_snapshot” parameter wherein you can add T-SQL to drop the constraint (link).
The issue of foreign keys on the subscribers in transactional or snapshot replication is actually quite debated. I personally am of the opinion they are a waste of resources and that if referential integrity is being maintained on the publishers PRIOR to replicating, then there is no need whatsoever for those keys on the subscribers. It gets a bit more complicated when dealing with merge replication due to the 2-way nature of the beast. What do you say we leave that conversation for another day, eh?
Thanks and have a Grateful day…Troy