I’m fairly new to SQL Server and am still learning some of the tricks of the trade, and the other guy who teaches me is out of work for the week, normally I’d run the statement by him first and then run it.
What I’m trying to do is delete everything that is returned in this select statement:
SELECT * from LOCATIONS a Join CONTACTS b on a.location_ID = b.Location_ID
join CONTACTS_SOURCES c on b.contact_ID = c.Contact_ID where c.Source_ID = 10014918
I need to delete what this statement returns from both the CONTACTS table and the LOCATIONS table. Which route would be the best route to take when doing this?
Route A:
delete from LOCATIONS a
Join CONTACTS b
on a.location_ID = b.Location_ID
join CONTACTS_SOURCES c
on b.contact_ID = c.Contact_ID where c.Source_ID = 10014918
or Route B.
DELETE from LOCATIONS where (SELECT * from LOCATIONS a
Join CONTACTS b
on a.location_ID = b.Location_ID
join CONTACTS_SOURCES c
on b.contact_ID = c.Contact_ID where c.Source_ID = 10014918)
DELETE FROM CONTACTS where (SELECT * from LOCATIONS a
Join CONTACTS b
on a.location_ID = b.Location_ID
join CONTACTS_SOURCES c
on b.contact_ID = c.Contact_ID where c.Source_ID = 10014918)
I have a feeling that Route A. will not delete from the LOCATIONS and CONTACTS table.
Your feeling is right: a DELETE query (any DML query, really) can only affect a single table. The problem with Route B is the second query won’t work because the first query deleted all the rows that would be candidates for the join.
How about: