Sql-server – Do i need “CHECK CONSTRAINT” when i am using “WITH CHECK ADD CONSTRAINT”

check-constraintsschemasql-server-2008-r2t-sql

I am working on SQL Server 2008 R2, where I generated a schema-only database script using SQL Server Management Studio. The generated script is as follows:

ALTER TABLE [dbo].[ConsoleServer]  WITH CHECK ADD  CONSTRAINT [FK_ConsoleServer_RackUnits] FOREIGN KEY([RackUnitID])
REFERENCES [dbo].[RackUnits] ([UnitID])

GO
ALTER TABLE [dbo].[ConsoleServer] CHECK CONSTRAINT [FK_ConsoleServer_RackUnits]

I have these 2 questions:-

  • I know that the first line is responsible to create a FK between two DB tables. but what is the purpose of the following :

    ALTER TABLE [dbo].[ConsoleServer] CHECK CONSTRAINT [FK_ConsoleServer_RackUnits]
    

    I mean since I have specified to add the constraint with check, why do i need to enable the constraint using check constraint ?

  • Second question: In general, why does the DB script has the word GO. Now if I remove it the script will be executed well on the destination DB, so why it is included in the script prior to any statement?

Best Answer

The answer to both of your questions is really the same. You are using a script generation tool. It does what it's told to do. Typically the second command is only needed if you are doing a WITH NOCHECK on the first one. However it's included because the settings for the script generation component of SSMS told it to include it.

Here is a post I did on modifying those settings.

As far as the GO command. This is a batch separator and is useful in breaking up a script both visually and for the computer. It ends the scope of variables and affects how the parser looks at your script. Again it's included because that is what the tool was told to do.