Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to recheck primary/foreign key constraint for data already in the table in sql server?

I have a table in SQL Server 2005 with a foreign key and it was disable for huge data loading, and then re-enabled:

Example:

alter table table1 nocheck constraint fk_1
go
lots of inserts...
go
alter table table1 check constraint fk_1
go

Now, the question: is there a way to re-check this just inserted data?

like image 535
Julio Furquim Avatar asked Jan 20 '23 08:01

Julio Furquim


1 Answers

The syntax looks a little silly with the word "check" repeated, but what you want is:

alter table table1 with check check constraint fk_1
go

Adding the "with check" option will validate existing data against the constraint. Doing this will also prevent the constraint from becoming untrusted.

If any existing data violates the constraint, you'll get an error that will look like this:

The ALTER TABLE statement conflicted with the CHECK constraint "fk_1".
like image 175
Joe Stefanelli Avatar answered Jan 31 '23 00:01

Joe Stefanelli