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.
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.
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.
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.
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
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>;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With