Search This Blog

Thursday, May 20, 2010

Adding foreign key to an existing table with data in Sql Server

If adding a foreign key to existing table, and it returns with this exception
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint
and you're positive the constraint should work, do it like that: first, create foreign key with nocheck option. This will add a constraint without checking data. Next, enable this constraint.

alter table tbl
with nocheck
add constraint fk_UserId foreign key (UserId) references tbl2(UserId);

ALTER TABLE tbl CHECK CONSTRAINT ALL;

No comments:

Post a Comment