I have a table with a lot of history entries that contain customer IDs.
There is a separate customer table. Occasionally some of the customer entries are removed.
Is there an easy way, without looping through each history entry, to drop all rows in the history table where the customer ID no longer exists because the customer row was deleted?
In SQL Server the correct way to avoid orphaned rows is to use DRI (Declared Referential Integrity) also known as foreign key constraints. When using DRI you can define what you want to happen when you update/delete a parent row(CASCADE options).
An orphan record is an imported transaction record that does not specify a site. To create a Maximo® database record from an imported record, you must specify a site on the transaction record.
delete from history_table where customer_id not in (select customer_id from customers)
did you mean something like this?
DELETE h.* FROM history h
LEFT JOIN customer c ON h.customer_id = c.id
WHERE c.id IS NULL
I'm typing this from the top of my head, but you get the idea hopefully.
Delete syntax documentation
How about:
DELETE FROM history_table
WHERE customer_id NOT IN (SELECT customer_id FROM customer);
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