WITH NOCHECK/CHECK
You can add or enable the constraint without checking existing rows,but the constraint will be marked as not trusted. If you try to add or enable a constraint checking existing rows, and there is a row breaking the constraint,then you will not be able to add or enable the Constraint
The below Example gives the Scenario:
CREATE TABLE Books
(Bookid INT IDENTITY(1,1) PRIMARY KEY,[Name] VARCHAR(25))
GO
CREATE TABLE Authors
(Sno INT IDENTITY(100,1),AuthorName VARCHAR(25),BookID INT)
---At this sage there no foreign key relation specified.
INSERT Books
([Name])
VALUES('Ten Commandments')
GO
INSERT Authors
(AuthorName,BookID)
VALUES('Sydney',10)---Data is inserted in both the Table.No relations defined so far.
----Now i want to define the relation based on Existing Tables and Data
First i ran this query to Create Foreign Key Relation.
ALTER TABLE Authors
ADD CONSTRAINT FK_Books_Bookid FOREIGN KEY(BookID) REFERENCES Books(BookID)--This is Giving me Error because alreay Data is there.So this script wont work
----After that run the below script.
ALTER TABLE Authors WITH NOCHECK
ADD CONSTRAINT FK_Books_Bookid FOREIGN KEY(BookID) REFERENCES Books(BookID)--Here Foreign key is created. It ignores existing data and Start working on New Data.
---To check this Foreignkey as not trusted foreign key we can use this.
SELECT [name], type_desc, is_disabled, is_not_trusted
FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID('Authors');
The below Example gives the Scenario:
CREATE TABLE Books
(Bookid INT IDENTITY(1,1) PRIMARY KEY,[Name] VARCHAR(25))
GO
CREATE TABLE Authors
(Sno INT IDENTITY(100,1),AuthorName VARCHAR(25),BookID INT)
---At this sage there no foreign key relation specified.
INSERT Books
([Name])
VALUES('Ten Commandments')
GO
INSERT Authors
(AuthorName,BookID)
VALUES('Sydney',10)---Data is inserted in both the Table.No relations defined so far.
----Now i want to define the relation based on Existing Tables and Data
First i ran this query to Create Foreign Key Relation.
ALTER TABLE Authors
ADD CONSTRAINT FK_Books_Bookid FOREIGN KEY(BookID) REFERENCES Books(BookID)--This is Giving me Error because alreay Data is there.So this script wont work
----After that run the below script.
ALTER TABLE Authors WITH NOCHECK
ADD CONSTRAINT FK_Books_Bookid FOREIGN KEY(BookID) REFERENCES Books(BookID)--Here Foreign key is created. It ignores existing data and Start working on New Data.
---To check this Foreignkey as not trusted foreign key we can use this.
SELECT [name], type_desc, is_disabled, is_not_trusted
FROM sys.foreign_keys
WHERE parent_object_id = OBJECT_ID('Authors');
Comments