Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete data with foreign key in SQL Server table

Tags:

sql-server

I'm going to delete data in an SQL Server table (parent) which has a relationship with another table (child).
I tried the basic Delete query. But it isn't working (and I know it won't).

DELETE FROM table WHERE ...

It returned following error

The DELETE statement conflicted with the REFERENCE constraint ...

I need to keep the table's schema. I know that I just need to add some words in the query, I've ever done this before, but I just couldn't recall it.

like image 975
Andha Avatar asked Nov 24 '11 01:11

Andha


People also ask

Can we delete a table with foreign key?

To delete a foreign key constraintIn Object Explorer, expand the table with the constraint and then expand Keys. Right-click the constraint and then click Delete. In the Delete Object dialog box, click OK.

Can we delete a row with foreign key?

Here, ON DELETE CASCADE is added because when any row is deleted in one table the same gets deleted in the foreign referenced tables that are referencing the primary key in that table. Step-4: Verifying the database : To view the description of the tables in the database using the following SQL query as follows.

How do I delete a row in a table that contains foreign keys to other tables?

DELETE FROM ReferencingTable WHERE NOT EXISTS ( SELECT * FROM MainTable AS T1 WHERE T1. pk_col_1 = ReferencingTable. pk_col_1 ); Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.


3 Answers

You can disable and re-enable the foreign key constraints before and after deleting:

alter table MyOtherTable nocheck constraint all
delete from MyTable
alter table MyOtherTable check constraint all
like image 80
Chris Fulstow Avatar answered Oct 13 '22 06:10

Chris Fulstow


You need to manually delete the children. the <condition> is the same for both queries.

DELETE FROM child
FROM cTable AS child
INNER JOIN table AS parent ON child.ParentId = parent.ParentId
WHERE <condition>;

DELETE FROM parent
FROM table AS parent
WHERE <condition>;
like image 26
Adam Wenger Avatar answered Oct 13 '22 06:10

Adam Wenger


If you wish the delete to be automatic, you need to change your schema so that the foreign key constraint is ON DELETE CASCADE.

For more information, see the MSDN page on Cascading Referential Integrity Constraints.

ETA (after clarification from the poster): If you can't update the schema, you have to manually DELETE the affected child records first.

like image 23
Alastair Maw Avatar answered Oct 13 '22 06:10

Alastair Maw