I have a very simple link table set up, I need to delete rows from all 3 tables
Table 1 – Assignment {assignment_id}
LinkTable – AssignmentTasks {assignment_id, task_id}
Table 2 – Tasks {task_id}
I can delete from Assignment and AssignmentTasks easily as I have the Id but I don’t have the list of Tasks related to this assignment.
I’ve built a cursor which returns all the task_ids related to an assignment, but I can’t remove them whilst the records in the link table refer to them. (I don’t think I can as the foreign key constraint should stop me deleting rows referenced elsewhere)
Do I need to store a list of task_ids, delete the assignment_tasks records, delete the assignment record then iterate through the stored list of task_ids and delete each task ? or is there a better way of doing this ?
Or you can turn foreign key constraint checking off temporarily:
But that shouldn’t be necessary.
The other issue here is that this is currently written as a many-to-many relationship. This would imply that multiple assignments could refer to a one task. It probably wouldn’t be OK to delete the task just because one of the assignments referencing it was deleted. Instead, you would need to check that the task is no longer referenced before deleting it.
Alternatively, if you really meant for each task to belong to only one assignment, you could set your schema up like this:
The
ON DELETE CASCADEbit causes the Task entry to be deleted in the event that the assignment it refers to is deleted. This only works if foreign key constraints are enabled, of course. If the assignment is being deleted by a trigger or due to some other cascade, you may need to enable recursive triggers as well withpragma recursive_triggers = on.Another possibility (if you want to retain the original schema) is to make the foreign key references in the AssignmentTask table do the cascading delete. That way those rows are deleted automatically as you delete the Tasks. Then you can delete the Assignment once all of those are taken care of.