I am trying to clean up a table where there are quite a few orphaned items.
I am approaching this by checking to see if there is a relationship to another table by looking for null values.
DELETE FROM table1
LEFT JOIN table2 ON table1.ID = table2.ID
WHERE table2.ID IS NULL
I get an error that the left outer join is not valid.
I am looking for suggestions on other ways that I can delete these orphans from this broken relationship
Right-click a database in SQL Server Object Explorer, and select Delete. Accept all the default settings in the Delete Database dialog, and click OK.
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).
The DELETE statement is used to delete existing records in a table.
ON DELETE CASCADE constraint is used in MySQL to delete the rows from the child table automatically, when the rows from the parent table are deleted.
If you want to use the same syntax, here is how it could have been:
DELETE a
FROM table1 a
LEFT JOIN table2 b
ON a.id = b.id
WHERE b.id IS NULL
try this:
DELETE FROM table1
WHERE NOT EXISTS (SELECT NULL FROM table2 WHERE table1.ID = table2.ID)
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