简体   繁体   中英

MS SQL Server - What is the value of WITH CHECK in a foreign key constraint?

When I have SQL Server Management Studio generate a table creation script for me, the foreign key constraints are a bit different than how I would write them.

Here is one:

ALTER TABLE [dbo].[GeoBytesCountries]  
WITH CHECK 
ADD CONSTRAINT [FK_GeoBytesCountries_MapReferenceId] 
FOREIGN KEY ([MapReferenceId])
REFERENCES [dbo].[GeoBytesMapReferences] ([MapReferenceId])
GO

ALTER TABLE [dbo].[GeoBytesCountries] 
CHECK CONSTRAINT [FK_GeoBytesCountries_MapReferenceId]
GO

I would write this foreign key constraint without "WITH CHECK" and the 2nd "CHECK CONSTRAINT" statement and expect to get the same functionality.

Can someone explain to me the value of the using "WITH CHECK" and a separate "CHECK CONSTRAINT" statement when you are writing a foreign key constraint for a table?

Or is the code below completely / functionally equivalent to the code above?

ALTER TABLE [dbo].[GeoBytesCountries]  
ADD CONSTRAINT [FK_GeoBytesCountries_MapReferenceId] 
FOREIGN KEY ([MapReferenceId]) 
REFERENCES [dbo].[GeoBytesMapReferences] ([MapReferenceId])
GO

The way I see it, the two step approach allows you to at least keep more "bad" data from getting in assuming the with check part fails. That is, your constraint will exist and apply to DML from that point forward, but you may have to do some cleanup on your existing data to make it a trusted constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM