无法与另一个表创建外键关系

时间:2018-05-25 11:54:41

标签: sql-server

我试图这样做,

CREATE TABLE [dbo].[tblPerson](
[ID] [int] NOT NULL,
[Personame] [varchar](50) NULL)
[Email] [varchar](50) NULL,
[GenderId] [int] NULL

CREATE TABLE [dbo].[tblGender]( [id] [int] NOT NULL, [Gender] nvarchar NOT NULL)

Alter table tblPerson Add Constraint tblPerson_GenderId_FK Foreign Key (GenderId) references tblGender(id)

我得到以下错误不确定为什么

  

Msg 547,Level 16,State 0,Line 2   ALTER TABLE语句与FOREIGN KEY约束冲突" tblPerson_GenderId_FK"。冲突发生在数据库" Sqlkudavenkat",table" dbo.tblGender",column' id'。

1 个答案:

答案 0 :(得分:1)

我怀疑tblGender是新表,在这种情况下,您需要在创建外键之前使用值填充它。

假设在tblPerson中你在GenderID

中使用了2个值
0 meaning male
1 meaning female

然后您的查询可能如下所示:

CREATE TABLE [dbo].[tblGender]( [id] [int] NOT NULL, [Gender] nvarchar(100) NOT NULL)

insert into tblGender(id, gender)
select distinct p.GenderID, 
       case when p.GenderID = 0 then 'Male' 
            when p.GenderID = 1 then 'Female'
            else 'it came from outer space' 
       end
from   tblPerson p

Alter table tblPerson Add Constraint tblPerson_GenderId_FK Foreign Key (GenderId) references tblGender(id)