0

I have code line like this:

  "select count(1) from tblEquipmentRegister where EquipmentID = " & Me.cmbEquipmentID.Value & " and StartTime is null"

which results this string:

  "select count(1) from tblEquipmentRegister where EquipmentID = 203203,16 and StartTime is null"

when I pass this string to function

  Public Function getOneValue(strSQL As String)
  Dim q As QueryDef
  Dim rec As Recordset
  Set q = CurrentDb.QueryDefs("qTmp")

  q.SQL = strSQL
  Set rec = q.OpenRecordset

  getOneValue = rec.Fields(0).Value

  Set q = Nothing
  Set rec = Nothing

  End Function

I get syntax error (comma) in query expression I don't get error if EquipmentID is number without a comma. How should I construct string with a comma in the EquipmentID?

1
  • Enclose the EquipmentId with in single quote. "select count(1) from tblEquipmentRegister where EquipmentID = '" & Me.cmbEquipmentID.Value & "' and StartTime is null" Commented Jan 9, 2015 at 6:42

2 Answers 2

2

If there is any possibility that EquipmentID could contain a single quote, the above code will fail.

I use a function qString to both wrap the string in quotes and to double-up any embedded quotes:

    ' Return string S quoted, with quotes escaped, for building SQL.
    ' O'Connor -> 'O''Connor'
    Public Function QString(ByVal s As String) As String
       QString = "'" & Replace(s, "'", "''") & "'"
    End Function

If all you want is the record count, you can get it much more easily with the DCount built-in function. This single statement will replace all of your code:

    getOneValue = DCount("*", "tblEquipmentRegister", _
                  "EquipmentID = " & QString(cmbEquipmentID) & _
                  " AND StartTime IS NULL")
Sign up to request clarification or add additional context in comments.

Comments

1
select count(1) from tblEquipmentRegister where EquipmentID = 203203,16 and StartTime is null

should be

select count(1) from tblEquipmentRegister where EquipmentID = '203203,16' and StartTime is null

In short

select * from table where val=number

is correct if value is integer.

but if it's a string then you should use

select * from table where val='some string'

So 203203,16 is string and 20320316 is number, that's why it works fine without comma.

So you should edit your code to

select count(1) from tblEquipmentRegister where EquipmentID = '" & Me.cmbEquipmentID.Value & "' and StartTime is null

2 Comments

then I get data type mismatch in criteria expression on the code line set rec = q.OpenRecordset
that's a must do, you can't enter string in integer data type.

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.