You could use a simple DELETE JOIN;
DELETE A FROM A
LEFT JOIN B ON A.itemnum = B.itemnum
LEFT JOIN C ON A.itemnum = C.itemnum
WHERE b.itemnum IS NULL
AND c.itemnum IS NULL;
Question
I am working on a SQL Server 2008 database where all items that can be used in the database are stored in table A with a key value of ItemNum. Table B and Table C use ItemNum as a key value and are where the items from table A are actually used. Table A contains many duplicates that aren't used in Table B and Table C. I need to delete all ItemNum from Table A that are not used in tables B or table C.
Right now I have the following two queries using Select
statements (which will eventually be switched to Delete
statements) which I am not sure are working correctly, and I want to create the most efficient query possible.
USE Database
GO
SELECT ItemNum
FROM B
WHERE EXISTS
(SELECT ItemNum FROM A WHERE A.ItemNum = B.ItemNum)
USE Database
GO
SELECT ItemNum
FROM C
WHERE EXISTS
(SELECT ItemNum FROM A WHERE A.ItemNum = C.ItemNum)
Solution
You could use a simple DELETE JOIN;
DELETE A FROM A
LEFT JOIN B ON A.itemnum = B.itemnum
LEFT JOIN C ON A.itemnum = C.itemnum
WHERE b.itemnum IS NULL
AND c.itemnum IS NULL;
OTHER TIPS
Something like this?:
DELETE FROM TableA WHERE ItemNum NOT IN(SELECT ItemNum FROM TableB) and ItemNum NOT IN(SELECT ItemNum FROM TableC)