简体   繁体   中英

VBA SQL missing last condition of WHERE clause

I have pulled the last of what little hair I have left out trying to get what I thought was a fairly simple SQL statement to run through VBA. When the string for the statement compiles, it is cutting off the last condition of the WHERE clause and I can't work out how to fix it. Please help!

My SQL string looks like this:

sSQL = "UPDATE Allocations SET WithdrawalDate =" & dThisWithdrawDate & ",Notes = '" & sNotes & "' WHERE StaffID =" & lID & " AND PatientID = " & lThisPatientID & ";"

The string compiles with the StaffID variable and cuts off the AND part of the clause. What am I doing wrong?

Another way, as @Kostas suggested is to use parameters:

Sub Test()

    Dim dThisWithdrawDate As Date
    Dim sNotes As String
    Dim lID As Long
    Dim lThisPatientID As Long

    dThisWithdrawDate = DateSerial(2018, 6, 10)
    sNotes = "This note's not possible without hassle in string concat."
    lID = 1
    lThisPatientID = 2

    With CurrentDb.CreateQueryDef("", _
        "Parameters WithdrawDate DateTime, PatientNotes Text(255), " & _
        "StaffIdentifier Long, PatientIdentifier Long; " & _
        "UPDATE Allocations SET WithdrawalDate = WithDrawDate, Notes = PatientNotes " & _
        "WHERE StaffID = StaffIdentifier AND PatientID = PatientIdentifier")

        .Parameters("WithdrawDate") = dThisWithdrawDate
        .Parameters("PatientNotes") = sNotes
        .Parameters("StaffIdentifier") = lID
        .Parameters("PatientIdentifier") = lThisPatientID
        .Execute

    End With

End Sub

Or you can use something like: With db.QueryDefs("DML_Update_AllocationTable") if using a stored query.

Try to do it somehow replicable:

Public Sub TestMe()

    Dim sSql As String
    Dim dThisWithdrawDate As String: dThisWithdrawDate = "foo"
    Dim sNotes As String: sNotes = "bar"
    Dim lID As Long: lID = 5
    Dim lThisPatientID As Long: lThisPatientID = 10

    sSql = "UPDATE Allocations SET WithdrawalDate =" & dThisWithdrawDate & ",Notes = '" & sNotes & "' WHERE StaffID =" & lID & " AND PatientID = " & lThisPatientID & ";"
    Debug.Print sSql

End Sub

The code above prints:

UPDATE Allocations SET WithdrawalDate =foo,Notes = 'bar' WHERE StaffID =5 AND PatientID = 10;

Thus, the AND clause is cut off from somewhere else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM