Pergunta

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?

Foi útil?

Solução

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 "

Outras dicas

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;

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 !

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top