gpt4 book ai didi

sql - 无法删除或修改或查看同表外键约束

转载 作者:行者123 更新时间:2023-12-04 18:25:27 25 4
gpt4 key购买 nike

无法访问我数据库中的同一个表外键约束。我无法删除它、禁用它、将它添加回去……如何删除它并重新添加它?

注意:我有几个版本的数据库都是用同一个脚本创建的。只有一个我看到了这种行为。在其他情况下,此 key 很容易添加和删除。

非常感谢。这是我运行的一些脚本和结果:

在过去的某个时刻,我运行了以下脚本:

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'

所有 3 个都没有返回。

这是怎么回事,我该如何解决?我需要访问此对象,将其删除并重新添加。
非常感谢!

最佳答案

我猜您的主数据库已损坏。你可能最适合 rebuilding it .

但是,作为一种解决方法,您可以尝试这样做:

  1. 将您的外键复制到非 FK 列中

    ALTER TABLE Recipe ADD DuplicateOfFK INT

  2. 将所有 FK 数据复制到副本

    更新食谱 SET DuplicateOfFK = DuplicateOfRecipeId

  3. 删除外键列

    ALTER TABLE Recipe DROP COLUMN DuplicateOfRecipeId

  4. 向后走。

    ALTER TABLE Recipe ADD DuplicateOfRecipeId INT

    更新食谱 SET DuplicateOfRecipeId = DuplicateOfFK

    ALTER TABLE Recipe DROP COLUMN DuplicateOfFK

  5. 重新添加约束。

关于sql - 无法删除或修改或查看同表外键约束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7116839/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com