On a project I’m working on we’ve got some tables with numerous foreign key relationships, and because it’s in early development the number of relationships will likely change.
We’d like to be able to delete records from certain tables but are reluctant to set up cascading deletes on the foreign key relationships.
We’ve considered the following options:
- Ignore our instincts and set up cascading deletes anyway
- Instead of a cascading delete use set null
- Write and maintain a custom script to delete all the foreign key records manually
None of these options are great 🙁
- We don’t want to set up cascading deletes because we don’t want that to be the default behaviour.
- We don’t want to use cascading nulls becuase leaving lots of orphans would be useless.
- Writing a custom script would work, but it’s not very scalable or maintainable. Writing a script for a single table or even a few tables is ok, but for every table? Seriously? There must be a better way! At least I hope there’s a better way.
For the “Too Long Didn’t Read” crowd; A quick summary
Is there a way of specifying that you’d like a delete to cascade, on a query by query basis?
Perhaps something that looks like this:
-- wouldn't it be nice if this was a real command!
CASCADE DELETE FROM MyTable WHERE ID = @ID
I am not sure I really see the usefulness of manual cascade option in your case.
The CASCADE is there to maintain certain relationships between entities and if you, and I quote,
that then you can still:
CALL CASCADE_DELETE('table_name', 'id = 3')(and you get a single point where you would maintain your clean-up scripts)But, please note that basically you are increasing complexity of the system because of what might be simply unfinished system design. That will not really help you in the long run and the design decisions should be addressed before hacking the functionality (if at all possible).
EDIT:
If the purpose is to clean test data to conform to the actual integrity rules then you could create a proper tables with proper rules and then move the data from test data tables to proper tables.
Rows that don’t conform to the proper integrity will fail the insert and you will have the clean data.