use*_*206 1 sql-server sql-server-2005 foreign-keys foreign-key-relationship sql-server-2008
我试图创建一个具有一对多关系的表.但似乎在Personal中添加外键不起作用.我想将个人信息表链接到地址表?这个错误的解决方案是什么?
Address 表已成功保存Personal 表无法创建关系'FK_Personal_Address'.
无法在引用列"Personal.ID"为标识列的位置创建级联外键"FK_Personal_Address".无法创建约束.查看以前的错误.
Person表中的主键可能是一个标识.这是一个自动递增的整数字段.
您需要在int类型的地址表中创建外键,而不是identity.它将保存与Person记录对应的整数,但您不希望外键自动递增.对于子表(地址)中的每个记录,您将为外键设置一个特定值,以指示它所属的父记录(Person).
例:
INSERT person (firstname, lastname) VALUES ('John', 'Smith')
Run Code Online (Sandbox Code Playgroud)
这将插入新的人员记录,并且该字段personid将自动填充,因为它是IDENTITY 字段.
现在要插入约翰史密斯的地址,你需要知道他的personid.例如:
-- Say, for example, personid of John Smith is 55
INSERT address (personid, street, city) VALUES (55, 'High Street', 'London')
Run Code Online (Sandbox Code Playgroud)
因此,在person表格中会自动生成personid,但在address表格中您指定与现有人员匹配的值.这是外键的重点.
如果没有关于模式的更多信息,很难猜出问题.
我确保遵循上面答案中讨论的身份、整数和主键。但是,我仍然遇到同样的错误。
'xReason' table saved successfully
'xAddress' table
- Unable to create relationship 'FK_xAddress_xReason'.  
The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_xAddress_xReason". The conflict occurred in database "databaseName", table "dbo.xReason", column 'xReasonID'.
Run Code Online (Sandbox Code Playgroud)
当我将一些数据插入Reason table.(具有主键的表)时,此错误得到解决
如果您读到这里,这可能是您的问题。