views:

23

answers:

1

I have a table with a whole bunch of FKs.

Table Vehicles
-----------
ColorID -> Color.ID
MakeID -> Make.ID
ModelID -> Model.ID
etc...

My issue is that I forgot a few columns and I need to add them. I can add them through right clicking on the table and choosing 'Design', but not if I want to make them NOT NULL, or delete a column. I could also generate a Drop/Create Script, but I get this Error:

Msg 3726, Level 16, State 1, Line 4
Could not drop object 'dbo.SellVehicles' because it is referenced by a FOREIGN KEY constraint.

Do I need to go through and remove each FK and then drop/create, then add them back or is there a quick/painless way of doing this? Is there a way to drop and recreate these FKs quickly?

Why doesn't

IF  EXISTS (SELECT * FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_SellVehicles_Conditions]') AND parent_object_id = OBJECT_ID(N'[dbo].[SellVehicles]'))
ALTER TABLE [dbo].[SellVehicles] DROP CONSTRAINT [FK_SellVehicles_Conditions]
GO

eliminate this error? Is the FK still on the other table being referenced?

+4  A: 

The constraint that is triggering the error is not on the dbo.SellVehicles table; it's on a table that references the dbo.SellVehicles table. The references to the Color, Make and Model tables aren't the issue--you're attempting to drop/delete the child in a parent-child relationship.

I doubt the constraint you test for existed prior to the ALTER TABLE ... DROP CONSTRAINT ....

In SSMS, you can right click on a table, and select "Dependencies". There's a radio button to select viewing the objects that depend on the dbo.SellVehicles table, or the stuff that the dbo.SellVehicles table depends on.

OMG Ponies
@Blankasaurus: Yes, you have to remove/disable the dependency on the `dbo.SellVehicles` table before you will be able to drop it.
OMG Ponies
It was a FK contraint on the parent table that referenced the table I was trying to modify. So, say I had 20 dependencies, is there a quick way to generate a script that would drop / create all the FKs on those tables that depended on the table I was trying to modify?
Blankasaurus
Disable... Is that "Enforce FK Contraint" = No?
Blankasaurus