Cannot create a foreign key becaue it is in conflict with itself

旧城冷巷雨未停 提交于 2019-12-12 05:49:20

问题


I am trying to add a Foreignkey to a table and i cannot because i get this error:

Msg 547, Level 16, State 0, Line 1 The ALTER TABLE statement conflicted with the FOREIGN KEY constraint "FK_RDATA_COMBO_VALUES_ID_REFERENCES". The conflict occurred in database "MyDatabase", table "dbo.EVA_REFERENCES", column 'ID_REFERENCES'.

The error message says that the problem is a conflict with FK_RDATA_COMBO_VALUES_ID_REFERENCES but this is the name of the FK i am trying to create, it does not exist yet.

This is my table:

CREATE TABLE [dbo].[RDATA_COMBO_VALUES](
    [ID_RDATA_COMBO] [int] IDENTITY(1,1) NOT NULL,
    [ID_REF_CDATA] [int] NOT NULL,
    [ID_MODULE_REC_ID] [int] NOT NULL,
    [VALUE] [nvarchar](max) NULL,
    [ID_REFERENCES] [int] NOT NULL,
 CONSTRAINT [PK_RDATA_COMBO_VALUES] PRIMARY KEY CLUSTERED 
(
    [ID_RDATA_COMBO] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

GO

ALTER TABLE [dbo].[RDATA_COMBO_VALUES]  WITH CHECK ADD  CONSTRAINT [FK_RDATA_COMBO_VALUES_ID_REF_CDATA] FOREIGN KEY([ID_REF_CDATA])
REFERENCES [dbo].[EVA_REFERENCE_CDATA] ([ID_REF_CDATA])
GO

ALTER TABLE [dbo].[RDATA_COMBO_VALUES] CHECK CONSTRAINT [FK_RDATA_COMBO_VALUES_ID_REF_CDATA]
GO

And this is the command i use to create the FK:

ALTER TABLE [dbo].[RDATA_COMBO_VALUES]  WITH CHECK ADD  CONSTRAINT [FK_RDATA_COMBO_VALUES_ID_REFERENCES] FOREIGN KEY([ID_REFERENCES])
REFERENCES [dbo].[EVA_REFERENCES] ([ID_REFERENCES])

Why the ALTER TABLE statements is in conflict with the FK i still not created?

UPDATE: this question has a continuation in this one that originated allmy questions about this table.


回答1:


The message could be misleading but the FK i am trying to add is in conflict with the data, because the field contains values that does not exist in the referenced table.

Before creating the FK it is necessary to remove orphans.



来源:https://stackoverflow.com/questions/44067187/cannot-create-a-foreign-key-becaue-it-is-in-conflict-with-itself

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!