The MSDN claims that the order is :
- Child table: delete records.
- Parent table: insert, update, and delete records.
- Child table: insert and update records.
I have a problem with that.
Example : ParentTable have two records parent1(Id : 1) and parent2(Id : 2)
ChildTable have a record child1(Id : 1, ParentId : 1)
If we update the child1 to have a new parent parent2, and then we delete parent1.
- We have nothing to delete in child table
- We delete parent1 : we broke the constraint, because the child is still attached to parent1, unless we update it first.
So what is the right order, and is the MSDN false on the subject?
My personnals thoughts is
- Child table: delete records.
- Parent table: insert, update records.
- Child table: insert and update records.
- Parent table: delete records.
But the problem is, with potentially unique constraint, we must always delete the records in a table before adding new… So I have no solution right now for commiting my datas to my database.
Edit : thanks for the answers, but your corner case is my daily case… I opt for the ugly solution to disabled constraint, then update database, and re-enabled constraint. I’m still searching a better solution..
Doesn’t your SQL product support deferred constraint checking ?
If not, you could try
Delete all child records – delete all parent records – insert all parent records – insert all child records
where any UPDATEs have been split into their constituent DELETEs and INSERTs.
This should work correctly in all cases, but at acceptable speeds probably in none …
It is also provable that this is the only scheme that can work correctly in all cases, since :
(a) key constraints on parent dictate that parent DELETES must precede parent INSERTS,
(b) key constraints on child dictate that child DELETES must precede child INSERTS,
(c) FK dictates that child DELETES must precede parent DELETES
(d) FK also dictates that child INSERTS must follow parent INSERTS
The given sequence is the only possible one that satisfies these 4 requirements, and it also shows that UPDATEs to the child make a solution impossible no matter what, since an UPDATE means a “simultaneous” DELETE plus INSERT.