Sunday, March 25, 2012

Delete all records in tblA not matching in tblB

I'm hoping someone can tell me how to construct a stored procedure that
deletes all records in tblA not matching the PK in tblB

This gives me the recordset of all records in tblA with no matching
records in tblB (ID is the PK in tblB)

SELECT a.ID
FROM dbo.tblB b
RIGHT OUTER JOIN dbo.tblA a ON b.ID = a.ID
WHERE
b.ID IS NULL

thanks,
lqDELETE FROM tblA
WHERE NOT EXISTS
(SELECT *
FROM tblB
WHERE tblB.id = tblA.id)

(Untested. Make sure you have a current backup and test it out for
yourself first.)

--
David Portas
SQL Server MVP
--|||Thanks for that. I have never used NOT EXISTS before. lq

No comments:

Post a Comment