3

I have the following code in VBA:

Dim strSQL As String
strSQL = "UPDATE Workstations SET MID = newvalue WHERE MID = tempvalue"
DoCmd.RunSQL strSQL

newvalue and tempvalue are both global variables and have already been set values. Syntax wise, does this make sense? or am I missing quotation marks?

1 Answer 1

9

Try this one:

If MID is number:

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = " & newvalue & " WHERE [MID] = " & tempvalue
DoCmd.RunSQL strSQL

If MID is string (if newvalue/tempvalue doesn't contain single quote '):

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = '" & newvalue & "' WHERE [MID] = '" & tempvalue & "'"
DoCmd.RunSQL strSQL

If MID is string (if newvalue/tempvalue contains single quote ' like newvalue="Mike's car"):

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = '" & Replace(newvalue, "'", "''") & "' WHERE [MID] = '" & Replace(tempvalue, "'", "''") & "'"
DoCmd.RunSQL strSQL

If MID is date:

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = #" & newvalue & "# WHERE [MID] = #" & tempvalue & "#"
DoCmd.RunSQL strSQL

Thanks to @HansUp for pointing out in comments, that

MID is the name of a function, so it would be safer to bracket or alias that field name in the SQL statement: SET [MID]

Sign up to request clarification or add additional context in comments.

5 Comments

MID is the name of a function, so it would be safer to bracket or alias that field name in the SQL statement: SET [MID] and WHERE [MID] Better yet, rename the field with a name which is not a reserved word.
Thanks, @HansUp, that make sence. Updated my answer.
What's going to happen if newvalue or tempvalue are strings with single quotes? You should also escape them, or better, switch to parameterized statements.
thank you so much! really went in depth here. I probably should have specified MID is a number field. Thanks again!
Rather than bracketing fields / columns, it is best to prefix with an alias UPDATE Workstations w SET w.MID , this scales nicely to other servers and you need never worry about reserved words again.

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.