I have a Visual Studio database project with a series of tables that have foreign key constraints.
The publish script includes the add constraint script:
ALTER TABLE [dbo].[AttributeValue] WITH NOCHECK
ADD CONSTRAINT [FK_AttributeValue_Attribute]
FOREIGN KEY ([AttributeId]) REFERENCES [dbo].[Attribute] ([AttributeId]);
And right at the end of the script it enabled the constraint:
ALTER TABLE [dbo].[AttributeValue] WITH CHECK CHECK CONSTRAINT [FK_AttributeValue_Attribute];
The problem is, it fails to enable the constraint because it thinks it doesn’t exist. If I check the table I can confirm it doesn’t exist.
Why has the constraint not been created?
If I run the scripts in isolation, the create works and the enable works.
This really is going to be an entry for the daily WTF.
Someone has added a post-build script to the project, which performs the following steps.
DROPS all constraints by inspecting the system tables
Adds some data
Attempts to CREATE the constraints again by inspecting the system tables
Of course, step 3 does nothing because there is nothing to find in the system tables, given that it removed everything in step 1.
I am truly stunned by this plan and will replace it with the following:
Step 1
Step 3