1

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
4

1 回答 1

0

在我看来,两步方法至少可以让您在假设with check部件出现故障的情况下防止更多“坏”数据进入。也就是说,您的约束将存在并从那时起应用于 DML,但您可能必须对现有数据进行一些清理以使其成为受信任的约束。

于 2013-06-23T15:54:37.857 回答