更新WHERE子句中的语法错误

时间:2016-03-29 18:37:52

标签: ms-access access-vba ms-access-2016

从查询生成报告;从几个表中捕获数据。报告有两个计算框,我想将UPDATE数据返回到其中一个表。调试显示我正在捕获变量,但在WHERE子句中不断给出语法错误。我在网上搜索过很多语法迭代。

Private Sub Report_Load()
Dim sqls As String
Dim TEP As Single
Dim PPS As Single
Dim RecipeN As String
TEP = Reports![RecipeBuild]![txtTEP]
PPS = Reports![RecipeBuild]![txtPPS]
RecipeN = Reports![RecipeBuild]![RecipeName]
sqls = "Update [tblRecipeBuild] " _
    & "Set TEP = " & TEP & " " _
    & "Set PPS = " & PPS & " " _
    & "WHERE [RecipeName] = '" & RecipeN & "';"
DoCmd.SetWarnings False
DoCmd.RunSQL sqls
DoCmd.SetWarnings True
End Sub

1 个答案:

答案 0 :(得分:2)

Access SQL UPDATE只应包含SET个关键字一次。

如果要更新多个字段,请使用SET一次,然后在 FieldName = Value 段对之间使用逗号。

sqls = "Update [tblRecipeBuild] " _
    & "Set TEP = " & TEP & ", PPS = " & PPS & " " _
    & "WHERE [RecipeName] = '" & RecipeN & "';"

我认为这应该有效,但建议您考虑参数查询,而不是将值连接到UPDATE语句中。

Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim strUpdate As String
strUpdate = "UPDATE tblRecipeBuild SET TEP=pTEP, PPS=pPPS WHERE RecipeName=pRecipeN;"
Debug.Print strUpdate
Set db = CurrentDb
Set qdf = db.CreateQueryDef(vbNullString, strUpdate)
With qdf
    .Parameters("pTEP").Value = TEP
    .Parameters("pPPS").Value = PPS
    .Parameters("pRecipeN").Value = RecipeN
End With
qdf.Execute dbFailOnError