I am trying to clean up a database with a load of crap records in it,
It is of a relational structure and there are foreign keys linking everything together, I have got a delete command set up:
DELETE FROM Members
WHERE (CurrentClass = 339) AND (YEAR(LastSessionDate) < 2011)
The DB structure looks like this:
Members
-----------------------------------------------------------------------
Id ¦ FirstName ¦ LastName ¦ JoiningClass ¦ CurrentClass ¦ CurrentScheme
-----------------------------------------------------------------------
0 ¦ Fakey ¦ McFake ¦ 123 ¦ 999 ¦ 2
-----------------------------------------------------------------------
1 ¦ Fakette ¦ McFake ¦ 123 ¦ 998 ¦ 1
-----------------------------------------------------------------------
The above table references tables Classes and Pricing on the fields JoiningClass, CurrentClass and CurrentScheme those tables then reference other tables with fields they hold, so basically everything references everything.
I want to delete the above records that match criteria of mine but I get a foreign key warning.
I had considered adding:
ON DELETE CASCADE
To it but I am afraid as everything references everything else it will delete ALL of the database data.
I.E. If I delete record 0 above that it will delete the classes 123 and 999 and that will in turn delete all of its references.
Does this happen or should I know better?
If “everything references everything” as you say, then it’s hard to tell what would happen exactly without some serious (read: time consuming, annoying) analysis of the schema. The same goes for using 3rd party tools – you’re never 100% sure what they’ll do exactly, and deleting records isn’t something you want to risk on a production database.
Instead, you should create another copy of your database (backup your schema, then recreate it from backup on another server), add your cascading triggers and see what happens.