I need to write an SQL script that selects one record in table1, then does a lookup in the remaining tables in the database. If it doesn't find the record, I need delete the record from table1. Anyone provide some sample script?
+3
A:
One example
delete table1
where not exists (select 1
from Table2
where table1.SomeColumn = Table2.SomeColumn)
AND table1.SomeColumn = 5 --just an example,
Leave the AND out if you want to delete all the rows from table 1 that do not exist in table 2
you can also use LEFT JOIN or NOT IN
SQLMenace
2010-06-08 14:21:15
+2
A:
I have done things like this:
DELETE table1
FROM table1
WHERE table1.ID NOT IN (
SELECT RefID FROM Table2
UNION
SELECT RefID FROM Table3
...
)
Assuming RefID are FK's to table1.ID. Is this what you need?
n8wrl
2010-06-08 14:21:36
This would work well if checking against multiple tables. I'd make it a "UNION ALL", of course.
Philip Kelley
2010-06-08 14:24:42
+1
A:
DELETE FROM Table1 WHERE id=10 AND NOT EXISTS (SELECT * FROM Table2 WHERE id=10);
Sjoerd
2010-06-08 14:21:37
+1
A:
Very generally, (since you gave little details)
Delete Table1 t1
Where [Criteria to find table1 Record]
And Not Exists(Select * From Table2
Where pk = t1.Pk)
And Not Exists(Select * From Table3
Where pk = t1.Pk)
And Not Exists(Select * From Table4
Where pk = t1.Pk)
... etc. for all other tables
Charles Bretana
2010-06-08 14:23:34
@VeeArr: We have a database that has purged records from all tables based on a date timestamp, but there is one table that has no date timestamp. I need to delete records from here that do not exist anywhere else.@HLGEM: I don't need to do one record at a time, but i just wanted to get a base script down. I've done selects and deletes where records exist, but not the opposite. There are approximatley 10 tables that I'm looking up.@Martin Smith: Yes.
jerle78
2010-06-08 14:29:43