I have the table with one primary key
and one foreign key
referencing the same table primary key
.
i.e there are parents and childs in the same table. In sql sever there are three options for the delete rule. But it is only possible to set "NO ACTION"
delete rule. I understand that it is not possible to set the "cascade" delete
because of cycles and chaining. But why the other options are not allowed? Especially the "SET NULL"
one.
Right now I have to do this manually. I have to find the child records and set the foreign key on null. After that I can delete the parent. Why is it not possible to set the rule for it?
SET NULL. It is used in conjunction with ON DELETE or ON UPDATE. It means that the child data is set to NULL when the parent data is deleted or updated.
What is a foreign key with "Set NULL on Delete" in Oracle? A foreign key with "set null on delete" means that if a record in the parent table is deleted, then the corresponding records in the child table will have the foreign key fields set to null. The records in the child table will not be deleted.
ON DELETE CASCADE : SQL Server deletes the rows in the child table that is corresponding to the row deleted from the parent table. ON DELETE SET NULL : SQL Server sets the rows in the child table to NULL if the corresponding rows in the parent table are deleted.
The delete rule works as follows: With RESTRICT or NO ACTION, an error occurs and no rows are deleted. With CASCADE, the delete operation is propagated to the dependents of p in table D. With SET NULL, each nullable column of the foreign key of each dependent of p in table D is set to null.
Because it cannot perform two actions on the same table together which are:
-delete the parent.
-update the children.
A mutating table is a table that is being modified by an UPDATE, DELETE, or INSERT statement, or a table that might be updated by the effects of a DELETE CASCADE constraint.
you can overcome doing it manually by creating a procedure that would hold the parent key to delete the record and set the children to NULL.
procedure(parent_id) --takes the id as a parameter
update table set null where foreign_key = parent_id;
delete from table where id = parent_id;
end;
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