I created a table with a foreign key constraint on it. When I generate a table creation script through SSMS, it creates the following code:
ALTER TABLE [dbo].[MainTable] WITH CHECK ADD CONSTRAINT [FK_MainTable_ForeignKeyTable] FOREIGN KEY([FK_Field])
REFERENCES [dbo].[ForeignKeyTable] ([PK_Field])
GO
ALTER TABLE [dbo].[MainTable] CHECK CONSTRAINT [FK_MainTable_ForeignKeyTable]
GO
Since the first statement creates the constraint WITH CHECK, does this make the second statement redundant? If not, what is the CHECK CONSTRAINT accomplishing that the WITH CHECK does not?
I saw ALTER TABLE CHECK CONSTRAINT, but in that case, the SSMS is generating the first statement WITH NOCHECK, so it makes sense to have both statements.
Best Answer
The first statement alters the table to add the constraint. The second statement enables or disables the constraint for future inserts or updates.
So,
ALTER TABLE ... CHECK CONSTRAINT ...
enables the constraint for future inserts/updates. If you specifyALTER TABLE ... NOCHECK CONSTRAINT ...
, that disables the constraint, thereby allowing future inserts and updates to succeed even if the column in the table referenced by the foreign key does not contain a matching value. You can see the utility of having both statements present through this example:So, we created two tables that do not have a defined relationship. Later, we decide we want to design-in the relationship, so we add a foreign key in
dbo.b
that references the primary key column indbo.a
. We want the existing rows to be checked for validity, but don't care about new rows that might get added in future1.All good. The existing rows were validated, and new rows won't be validated against the foreign key:
The table contents:
Results:
So, since the code that scripts tables in SSMS has to cover every eventuality, it spits out a
ALTER TABLE ... CHECK CONSTRAINT ...
even if it's not required, and in the vast majority of cases is certainly not required.1 - why anyone would want existing rows to be validated, but not care about new rows is a little mysterious, but there you go.