无法访问数据库中的同一表外键约束。我无法删除它,禁用它,将其添加回,…如何删除它并重新添加它?
注意:我有多个数据库版本,都是使用相同的脚本创建的。我只有一个人看到这种行为。在其他情况下,可以轻松添加和删除此密钥。
非常感谢。这是我运行的一些脚本和结果:
在过去的某个时候,我运行了以下脚本:
ALTER TABLE Recipe ADD CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id FOREIGN KEY (DuplicateOfRecipeId) REFERENCES Recipe (Id) ;
现在正在运行
ALTER TABLE Recipe DROP CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id results in the following error: 'FK_Recipe_DuplicateOfRecipeId_Recipe_Id' is not a constraint.
并运行
ALTER TABLE Recipe NOCHECK CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id results in: Constraint 'FK_Recipe_DuplicateOfRecipeId_Recipe_Id' does not exist.
所以我跑
alter table Recipe ADD CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id FOREIGN KEY (DuplicateOfRecipeId) REFERENCES Recipe (Id);
我得到:
The ALTER TABLE statement conflicted with the FOREIGN KEY SAME TABLE constraint "FK_Recipe_DuplicateOfRecipeId_Recipe_Id". The conflict occurred in database "CrawlerDB", table "dbo.Recipe", column 'Id'.
所以我跑:
select COUNT(*) from sys.objects where name = 'FK_Recipe_DuplicateOfRecipeId_Recipe_Id' select COUNT(*) from sys.all_objects where name = 'FK_Recipe_DuplicateOfRecipeId_Recipe_Id' SELECT COUNT(*) FROM sys.foreign_keys where name = 'FK_Recipe_DuplicateOfRecipeId_Recipe_Id'
所有三个都不返回。
怎么回事,我该如何解决?我需要访问该对象,将其删除并添加回去。 非常感谢!
我猜您的主数据库已损坏。重建它可能是最合适的选择。
但是,作为解决方法,您可以尝试以下操作:
ALTER TABLE Recipe ADD DuplicateOfFK INT
UPDATE Recipe SET DuplicateOfFK = DuplicateOfRecipeId
ALTER TABLE Recipe DROP COLUMN DuplicateOfRecipeId
ALTER TABLE Recipe ADD DuplicateOfRecipeId INT
UPDATE Recipe SET DuplicateOfRecipeId = DuplicateOfFK
ALTER TABLE Recipe DROP COLUMN DuplicateOfFK