I have a 3 tables that look like this:
(source: InsomniacGeek.com)
On the foreign keys I have set cascade deletes. Right now, when I delete a record in the Folder table, only the related record in the FolderItem is deleted.
This is expected and correct.
What I would to accomplish is when I delete a record in the Folder table, the corresponding records in the FolderItem and the Item table should be deleted.
How do I solve this? By adding a trigger that deletes all instances of Item with the FolderID in question? Or is there any better solution?
Use the ON DELETE CASCADE option to specify whether you want rows deleted in a child table when corresponding rows are deleted in the parent table. If you do not specify cascading deletes, the default behavior of the database server prevents you from deleting data in a table if other tables reference it.
A foreign key with cascade delete means that if a record in the parent table is deleted, then the corresponding records in the child table will automatically be deleted. This is called a cascade delete in SQL Server.
You need to decide what behavior you want exactly with the system. Your requirement sounds a bit abnormal and might indicate a mistake in db schema design. Why do you want to delete an Item when a related Folder is deleted? What if there is another Folder still related to that item, since it is a many-to-many relationship? In that case, deleting the Item will actually cause foreign key violation between Item and FolderItem. If the Items actually do belong under a specific Folder, aka one to many relationship, you will not need the FolderItem table at all.
I guess the mostly likely case is you want to delete the Item if there is no other FolderItem entries related to it. In that case, trigger is the appropriate solution, but you need to make sure you are checking for it in the trigger logic.
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