Wednesday, March 7, 2012

How to delete from two tables at once

I have 2 tables "Orders" and "OrderProducts"

In my application, there are moments when I clean up these tables.

There is a query that looks for some flag in the "Orders" table, and deletes the records.

But there are related (PK-FK) records in the "OrderProducts" table.

How can I delete also these records in the same query?

I suppose you use SQL 2005 and Sql Server management Studio. If so, then you must specify INSERT and UPDATE specification during the PK-FK constraint creation, and set the delete rule as 'cascade'. If you do so, then if you delete an 'order', then all the corresponding 'orderProducts' will also be deleted.

|||

Either delete all the records from the child table first or use the "ON DELETE CASCADE" method.

No comments:

Post a Comment