29

I have a table representing users. When a user is deleted I get:

DELETE statement conflicted with the REFERENCE constraint

Apparently, CASCADE DELETE is not as easy as I imagined in SQL Server, and the option needs to be added to the table.

The problem is: I cannot figure out how to add the CASCADE DELETE option.

I'm using: SQL Server 2008. Any ideas how to do this?

user2771704
  • 5,994
  • 6
  • 37
  • 38
RadiantHex
  • 24,907
  • 47
  • 148
  • 244

3 Answers3

32

Read this Microsoft article first. Read Me. I use the GUI during design so here is a picture of how it is selected in SSMS. alt text The syntax added to the foreign key is " ON DELETE CASCADE "

RC_Cleland
  • 2,274
  • 14
  • 16
20

Here's the way I would add the "cascading delete" feature to an existing foreign key in SQL Server Management Studio.

First, find your foreign key, and open it's "DROP and CREATE To" in a new Query window.

Drop and Create

Then, just add "ON DELETE CASCADE" to the "ADD CONSTRAINT" command:

On delete cascade

Then just hit hit the "Execute" button to run the query.

Job done !

Mike Gledhill
  • 27,846
  • 7
  • 149
  • 159
17

Google ALTER TABLE DROP CONSTRAINT, then ALTER TABLE ADD CONSTRAINT:

ALTER TABLE

Here's a quick example:

CREATE TABLE A 
(
 ID INTEGER NOT NULL UNIQUE
);

CREATE TABLE B 
(
 ID INTEGER NOT NULL UNIQUE
    CONSTRAINT fk__B__A 
       REFERENCES A (ID)
);

-- Oops! Forgot the CASCADE referential actions.
-- DROP the constraint then recreate it:

ALTER TABLE B DROP
   CONSTRAINT fk__B__A;

ALTER TABLE B ADD
   CONSTRAINT fk__B__A
      FOREIGN KEY (ID)
      REFERENCES A (ID)
      ON DELETE CASCADE
      ON UPDATE CASCADE;
onedaywhen
  • 55,269
  • 12
  • 100
  • 138
Mr. TA
  • 5,230
  • 1
  • 28
  • 35
  • 1
    I think what the RadiantHex means is RadiantHex wants to delete the rows associated with the constraint using cascading deletes not drop the constraints so the rows may be removed. – Mark Schultheiss Dec 15 '10 at 21:09
  • 4
    @Mark Schultheiss: I think what Mr. TA means is Mr. TA suggests the constraint cannot be altered (i.e. there is no `ALTER TABLE..ALTER CONSTRAINT` syntax), rather the constraint must be dropped then recreated. I've added an example for clarity. – onedaywhen Dec 16 '10 at 09:14