Link to home
Start Free TrialLog in
Avatar of pdvsa
pdvsaFlag for United States of America

asked on

Afterupdate cbo, Insert and text

Experts,

I have an error in an afterupdate query on a cbo to populate tblProjects.Buy_CP to the value on Me.cboBuy_CP.  
I think my problem is that Buy_CP is text and the single quote double quote is not correct in the below.  


    CurrentDb.Execute "UPDATE tblProjects SET Buy_CP='" & Me.cboBuy_CP.Column(1) & "' WHERE ID=" & Me.ID

Col 0 is the ID and Col 1 is the text.

Thank you...
SOLUTION
Avatar of John Tsioumpris
John Tsioumpris
Flag of Greece image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
It's always a good idea to create an extra SQL variable, but when you think the error comes from your UPDATE, then you need to look at your data. Cause your way of SQL string concatenation is vulnerable for SQL injection, thus it may fail due to single quotes in your data. Also as your ID seems to be numeric, enforcing this by using CLng() can help you to spot errors in data. And you need error handling with On [Local] Error GoTo LocalError (see attached file).

Dim Sql As String

Sql = "UPDATE tblProjects " & _
  "SET Buy_CP = '" & Replace(Me.cboBuy_CP.Column(1), "'", "''") & "' WHERE ID = " & CLng(Me.ID) & ";"
Debug.Print Sql
CurrentDb.Execute Sql

Open in new window

As ready to use-solution:

a) using a function for escaping quotes or NULL:

Dim Sql As String

Sql = "UPDATE tblProjects " & _
  "SET Buy_CP = " & SqlQuoteNull(Me.cboBuy_CP.Column(1)) & " WHERE ID = " & CLng(Me.ID) & ";"
Debug.Print Sql
CurrentDb.Execute Sql

Open in new window

b) with some error handling

Private Sub YourMethod()

  Const MSG_UPDATE_ERROR As String = "Error during update."
  Const SQL_UPDATE As String = "UPDATE tblProjects SET Buy_CP = {0} WHERE ID = {1};"

  If Not SqlExecuteFmt(SQL_UPDATE, SqlQuoteNull(Me.cboBuy_CP.Column(1)), CLng(Me.ID)) Then
    MsgBox MSG_UPDATE_ERROR, vbWarning
  End If

End Function

Open in new window

sql.vba
Avatar of pdvsa

ASKER

Thank you guys.... appreciate it much. I have not been able to get away to test  yet... shouod be able to tomorrow at latest. Enjoy the weekend!

Avatar of pdvsa

ASKER

my code was correct...my issue was something else.  Thank you...appreciate the advice and comments. 

In this case.. not really. Then there was "with some error handling" missing to catch the error where it really happened.