1

I have a DAO recordset that loops through a recordset and runs a SQL statement on another table, updating records of that table. For some reason, it doesn't like using the recordset value in the where clause of the SQL statement. I've tried everything I can think of.

strSQL = "Select A, B FROM TABLE1"
Set rs = CurrentDb.OpenRecordset(strSQL)
If Not rs.BOF and Not rs.EOF Then
 rs.MoveFirst
 While (Not rs.EOF)
  DoCmd.RunSQL "UPDATE TABLE2 SET TABLE2.B = rs!B WHERE TABLE2.A = rs!A;" 
  rs.MoveNext
 Wend
End If
rs.Close

The only trouble is the where clause. It has no problem with the set clause, even though it's accessing the value the same way. I get a datatype mismatch error on the where clause.

3
  • What are the field types for TABLE1.A and TABLE2.A ? Are they both strings? Commented Sep 8, 2017 at 16:25
  • you are not using the recordset values .... you are using the strings "rs!A" and "rs!B" .... you need to insert the values of rs!A and rs!B into the SQL query string ...... look up string concatenation on the internet Commented Sep 8, 2017 at 16:34
  • 1
    Good lord. Just write this as a single query. Doing this by looping through and building a SQL statement is crazy! Commented Sep 8, 2017 at 18:09

2 Answers 2

3

Just write a single query to do the whole thing and ditch the VBA code loop. The current version has security vulnerabilities, will perform badly, and is overly complicated for maintenance.

update Table2 
inner join Table1 on (Table1.A = Table2.A)
SET Table2.B = Table1.B
Sign up to request clarification or add additional context in comments.

1 Comment

fixed. Thanks for the assist.
1

Try it like this:

"UPDATE TABLE2 SET TABLE2.B = " & rs!B & " WHERE TABLE2.A = " & rs!A

And if they are strings, then you need to put them in single quotes like this:

"UPDATE TABLE2 SET TABLE2.B = '" & rs!B & "' WHERE TABLE2.A = '" & rs!A & "'"

Comments

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.