0

I need to delete all rows (records) from a table (Table2) that appear in another table (Table3) that have the same Code (present on Column "Code", with the same name for both tables).

I found a suggested solution in SQL:

DELETE Table2
FROM Table2
INNER JOIN Table3 ON Table2.Code = Table3.Code

My try in Access VBA.

DoCmd.RunSQL "DELETE * FROM Table2 INNER JOIN Table3 on Table2.Code = Table3.Code"

I get

runtime error "Specify the table containing the records you want to delete"

What I got partially working:

DoCmd.RunSQL "DELETE * FROM Table2 WHERE Table3.Code = Table3.Code"

This second code opens a popup asking for a parameter (what I want to match), which works, but I want to do that inputless.


Solution:

Adapting the code Doug Coats provided and "adapting" for Access VBA:

DoCmd.RunSQL "DELETE * FROM Table2 WHERE EXISTS ( SELECT Table3.Code FROM Table3 WHERE Table3.Code = Table2.Code )"
DoCmd.Requery

Added .Requery to remove the #Deleted that comes when deleting the records.

3
  • WHERE Table3.Code = Table3.Code any survivors? Commented May 11, 2021 at 7:19
  • Didn't understand the question greybeard Commented May 15, 2021 at 0:19
  • I can't imagine any record where Table3.Code does not equal Table3.Code, and this condition is presented in a DELETE * FROM Table2 as partially working: did any record survive this attempt? Commented May 15, 2021 at 3:59

1 Answer 1

1

Im generally not a fan of joining to a table just to check for the existence of some value.

Try using this instead:

    DELETE 
    FROM Table2 t2
    WHERE EXISTS
        (
            SELECT t3.Code 
            FROM Table3 t3 
            WHERE t3.Code = t2.Code
        )
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, got the code to work, only had to adapt for VBA as I have little knowledge. I'll be editing the question with the working code!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.