ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint [duplicate]

怎甘沉沦 提交于 2019-12-25 08:04:44

问题


I like to know if it's possible to create a self refering constraint using an ALTER TABLE statement. (tsql SQL Server 2012)

expected I have a table with just a Primary Key called ID and column called parent_id

I want to do something like this:

ALTER TABLE myTable
ADD CONSTRAINT FK_myTablemyTable
FOREIGN KEY (parent_Id)
REFERENCES myTable(Id)

but I just get the error:

The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint

Is there an alternative way to get the statement working, or do you have to recreate the whole table in this case ?

Hope somebody is able to help

Cheers


回答1:


Problem solved

I am creating some kind of table migration tool and have not realized that the data was inserted already ...

Problem was that the root element was Inserted with parent_id = 0 and not null...

So there is no mistake in the SQL statement.

now it's working



来源:https://stackoverflow.com/questions/41962457/alter-table-statement-conflicted-with-the-foreign-key-same-table-constraint

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