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
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>;
So, you need to DELETE related rows from conflicted tables or more logical to UPDATE their FOREIGN KEY column to reference other PRIMARY KEY's from the parent table.
Also, you may want to read this article Don’t Delete – Just Don’t
Set the FOREIGN_KEY_CHECKS before and after your delete SQL statements.
SET FOREIGN_KEY_CHECKS = 0;
DELETE FROM table WHERE ...
DELETE FROM table WHERE ...
DELETE FROM table WHERE ...
SET FOREIGN_KEY_CHECKS = 1;
Source: https://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys.
here you are adding the foreign key for your "Child" table
ALTER TABLE child
ADD FOREIGN KEY (P_Id)
REFERENCES parent(P_Id)
ON DELETE CASCADE
ON UPDATE CASCADE;
After that if you make a DELETE query on "Parent" table like this
DELETE FROM parent WHERE .....
since the child has a reference to parent with DELETE CASCADE, the "Child" rows also will be deleted! along with the "parent".
To delete data from the tables having relationship of parent_child, First you have to delete the data from the child table by mentioning join then simply delete the data from the parent table, example is given below:
DELETE ChildTable
FROM ChildTable inner join ChildTable on PParentTable.ID=ChildTable.ParentTableID
WHERE <WHERE CONDITION>
DELETE ParentTable
WHERE <WHERE CONDITION>
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