Can not delete or modify or see same table foreign key constraint

余生颓废 提交于 2019-12-05 22:42:48

I'm guessing that your master database is corrupted. You'd probably be best suited by rebuilding it.

However, as a workaround, you could try this:

  1. Duplicate your foreign key into a non-FK column

    ALTER TABLE Recipe ADD DuplicateOfFK INT

  2. Copy all your FK data to the duplicate

    UPDATE Recipe SET DuplicateOfFK = DuplicateOfRecipeId

  3. Drop the Foreign Key column

    ALTER TABLE Recipe DROP COLUMN DuplicateOfRecipeId

  4. Go backwards.

    ALTER TABLE Recipe ADD DuplicateOfRecipeId INT

    UPDATE Recipe SET DuplicateOfRecipeId = DuplicateOfFK

    ALTER TABLE Recipe DROP COLUMN DuplicateOfFK

  5. Add the constraint back.

Your comment above should have given you the clue:

after setting all values in the foreign key field to null, then everything works again. But why?

Unfortunately the error message can be misleading. The statement adding the foreign key back failed not because you were creating a circular reference, but because DuplicateOfRecipeId contained at least one non-null value that was not already contained in Id.

By that I mean that the following code works:

create table dbo.Recipe
(
    Id int not null identity(1, 1)
        constraint PK_Recipe primary key nonclustered
    , DuplicateOfRecipeId int not null
);
insert dbo.Recipe values (1), (2), (3);
alter table Recipe add constraint FK_Recipe_DuplicateOfRecipeId_Recipe_Id foreign key (DuplicateOfRecipeId) references Recipe (Id);
drop table dbo.Recipe
go

But the following code fails (note the different DuplicateOfRecipeId values):

create table dbo.Recipe
(
    Id int not null identity(1, 1)
        constraint PK_Recipe primary key nonclustered
    , DuplicateOfRecipeId int not null
);
insert dbo.Recipe values (4), (5), (6);
alter table Recipe add constraint FK_Recipe_DuplicateOfRecipeId_Recipe_Id foreign key (DuplicateOfRecipeId) references Recipe (Id);
drop table dbo.Recipe
go
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!