If I script a table with a foreign key, it looks like this:
GO
ALTER TABLE [dbo].[MyTable] WITH CHECK ADD CONSTRAINT [FK_MyTable_SomeCol] FOREIGN KEY([SomeCol])
REFERENCES [dbo].[MyOtherTable] ([SomeCol])
GO
ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_MyTable_SomeCol]
GO
What is the second part for (ALTER TABLE [dbo].[MyTable] CHECK CONSTRAINT [FK_MyTable_SomeCol]
)?
It's an artifact of the way that the constraint is scripted - although it's unnecessary to specify these options (since they're the defaults for new constraints), the same generator can also generate NOCHECK
options in exactly the same manner.
Documentation for ALTER TABLE
indicates two distinct uses of CHECK
/NOCHECK
:
WITH CHECK | WITH NOCHECK
Specifies whether the data in the table is or is not validated against a newly added or re-enabled
FOREIGN KEY
orCHECK
constraint. If not specified,WITH CHECK
is assumed for new constraints, andWITH NOCHECK
is assumed for re-enabled constraints.
And:
{ CHECK | NOCHECK } CONSTRAINT
Specifies that constraint_name is enabled or disabled.
So one option is saying "check the current contents of the table", the other is saying "Validate new data as it is added".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With