Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

T-SQL foreign key check constraint

When you create a foreign key constraint in a table and you create the script in MS SQL Management Studio, it looks like this.

ALTER TABLE T1  WITH CHECK ADD  CONSTRAINT FK_T1 FOREIGN KEY(project_id)
REFERENCES T2 (project_id)
GO
ALTER TABLE T1 CHECK CONSTRAINT FK_T1
GO

What I don't understand is what purpose has the second alter with check constraint. Isn't creating the FK constraint enough? Do you have to add the check constraint to assure reference integrity ?

Another question: how would it look like then when you'd write it directly in the column definition?

CREATE TABLE T1 (
my_column INT NOT NULL CONSTRAINT FK_T1 REFERENCES T2(my_column)
)

Isn't this enough?

like image 430
theSpyCry Avatar asked May 28 '10 08:05

theSpyCry


People also ask

Can a foreign key reference a unique constraint?

A UNIQUE constraint can be referenced by a FOREIGN KEY constraint. When a UNIQUE constraint is added to an existing column or columns in the table, by default, the Database Engine examines the existing data in the columns to make sure all values are unique.

What is the constraint of foreign key?

The FOREIGN KEY constraint is used to prevent actions that would destroy links between tables. A FOREIGN KEY is a field (or collection of fields) in one table, that refers to the PRIMARY KEY in another table.


2 Answers

First it creates the constraint and here you can specify whether data allready in the table should be checked or not against your new constraint. WITH { CHECK | NOCHECK }

The second part specifies that the constraint is enabled. ALTER TABLE TableName { CHECK | NOCHECK } CONSTRAINT ConstraintName

like image 50
Don Avatar answered Oct 23 '22 04:10

Don


The second statement is compelled by the "WITH CHECK" in the first statement. There is a setting you can toggle to not do this.

like image 39
Dane Avatar answered Oct 23 '22 03:10

Dane