A same table foreign key constraint in my database is not accessible. I can not drop it, disable it, add it back, … How do I remove it and re-add it?
Note: I have several versions of my database all created with the same script. Only in one I see this behavior. In others, this key is easily added and removed.
Many thanks. Here is some scripts I ran and the result:
At some point in the past i ran the following script:
ALTER TABLE Recipe
ADD CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id FOREIGN KEY (DuplicateOfRecipeId)
REFERENCES Recipe (Id) ;
now running
ALTER TABLE Recipe DROP CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id
results in the following error:
'FK_Recipe_DuplicateOfRecipeId_Recipe_Id' is not a constraint.
and running
ALTER TABLE Recipe NOCHECK CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id
results in: Constraint 'FK_Recipe_DuplicateOfRecipeId_Recipe_Id' does not exist.
so i run
alter table Recipe ADD CONSTRAINT FK_Recipe_DuplicateOfRecipeId_Recipe_Id FOREIGN KEY (DuplicateOfRecipeId) REFERENCES Recipe (Id);
and i get:
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'.
so I run:
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'
and all 3 return nothing.
Whats going on and how do I fix it? I need to access this object, remove it and add it back.
Many thanks!
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:
Duplicate your foreign key into a non-FK column
ALTER TABLE Recipe ADD DuplicateOfFK INTCopy all your FK data to the duplicate
UPDATE Recipe SET DuplicateOfFK = DuplicateOfRecipeIdDrop the Foreign Key column
ALTER TABLE Recipe DROP COLUMN DuplicateOfRecipeIdGo backwards.
ALTER TABLE Recipe ADD DuplicateOfRecipeId INTUPDATE Recipe SET DuplicateOfRecipeId = DuplicateOfFKALTER TABLE Recipe DROP COLUMN DuplicateOfFKAdd the constraint back.