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;

Leave a Reply

Your email address will not be published. Required fields are marked *