'not able to create Foreign key in sql server table

I have two table like this:

tblGender

enter image description here

and TblPerson

enter image description here

I want to set foreign key for GenderID.. but I'm getting this error:

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "tblPerson_GenderID_FK". The conflict occurred in database "Sample", table "dbo.tblGender", column 'id'.



Solution 1:[1]

You might have records in tblGender which don't have match in tblPerson on their respective columns.Try emptying the tables if that is an option.

Solution 2:[2]

This is the script to add foreign key constraint.

alter table TblPerson
add constraint tblPerson_GenderID_FK FOREIGN KEY ( GenderID) references tblGender(id)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mihai
Solution 2 Vijay Hulmani