我已经舍弃了我遗漏的最后一点,试图获得我认为可以通过VBA运行的相当简单的SQL语句。语句的字符串编译时,它切断了WHERE子句的最后一个条件,我不知道如何解决它。请帮忙!
我的SQL字符串如下所示:
sSQL = "UPDATE Allocations SET WithdrawalDate =" & dThisWithdrawDate & ",Notes = '" & sNotes & "' WHERE StaffID =" & lID & " AND PatientID = " & lThisPatientID & ";"
该字符串将使用StaffID变量进行编译,并切断该子句的AND部分。我在做什么错了?
答案 0 :(得分:3)
@Kostas建议的另一种方法是使用参数:
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
或者,如果使用存储的查询,则可以使用诸如With db.QueryDefs("DML_Update_AllocationTable")
之类的东西。
答案 1 :(得分:0)
尝试以某种方式可复制:
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
上面的代码打印:
UPDATE Allocations SET WithdrawalDate =foo,Notes = 'bar' WHERE StaffID =5 AND PatientID = 10;
因此,AND子句从其他地方断开。