Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a Foreign Key constraint with ON DELETE CASCADE not updating?

Tags:

sql

sql-server

We've realised in our SQL Server 2005 DB that some Foreign Keys don't have the On Delete Cascade property set, which is giving us a couple of referential errors when we try and delete some records.

Use the Management Studio I scripted the DROP and CREATESQL's, but it seems that the CREATE isn't working correctly.

The DROP:

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

and the CREATE

USE [FootprintReports]
GO
ALTER TABLE [dbo].[_SUBSCRIPTIONS]  WITH CHECK ADD  CONSTRAINT [FK__SUBSCRIPTIONS_Reports] FOREIGN KEY([PARAMETER_ReportID])
REFERENCES [dbo].[Reports] ([ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[_SUBSCRIPTIONS] CHECK CONSTRAINT [FK__SUBSCRIPTIONS_Reports]

If I manually change the value of the On Delete in the GUI, after dropping and recreating, the On Delete isn't correctly updated.

As a test, I set the Delete rule in the GUI to Set Null. It dropped correctly, and recreated without error. If I got back into the GUI, it is still showing the Set Null as the Delete Rule.

Have I done something wrong? or is there another way to edit a constraint to add the ON DELETE CASCADE rule?

like image 278
Alastair Pitts Avatar asked Apr 28 '10 05:04

Alastair Pitts


People also ask

Can foreign keys handle deletes and updates?

Foreign keys cannot handle deletes and updates. Explanation: A foreign key is the one which declares that an index in one table is related to that in another and place constraints.

What happens when you use on update cascade clause while defining foreign key?

UPDATE CASCADE: When we create a foreign key using UPDATE CASCADE the referencing rows are updated in the child table when the referenced row is updated in the parent table which has a primary key.

What happens when specifying on delete cascade for a foreign key column?

If you specify this option, when you delete a row in the parent table, the database server also deletes any rows associated with that row (foreign keys) in a child table. The advantage of the ON DELETE CASCADE option is that it allows you to reduce the quantity of SQL statements needed to perform delete actions.


1 Answers

Your approach looks correct. ALTER TABLE is the only way to edit a constraint. Perhaps Management Studio is needs a data refresh. Try right-click Refresh, or close the app and reopen it.

like image 162
Anthony Faull Avatar answered Oct 04 '22 00:10

Anthony Faull