从VB多个where条件更新SQL表

时间:2018-02-02 15:26:56

标签: sql vba sql-update

我正在尝试从VBA更新SQL表(使用下面的代码),似乎无法正确使用它。我想根据A,B,C,D,E的搜索条件更新第一列,第二列,第三列和第四列。我在这里出错了什么?没有给出错误,但表格没有更新?感谢

Sub UpdateData(A As String, B As String, C As String, D As String, E As String, one As Double, two As Double, three As Double, four As Double)

Dim sA As String, sB As String, sC As String, sD As String, sDesk As String, sE As String
Dim sone As Double, stwo As Double, sthree As Double, sfour As Double

Dim objConn As ADODB.Connection
Set objConn = New ADODB.Connection
objConn.ConnectionString = "Provider=SQLOLEDB;Data Source=source;Initial Catalog=Model_table;Integrated Security=SSPI"
objConn.Open
Set objRec = New ADODB.Recordset


Date = Format(Range("date").Value, "YYYY-MM-DD")
sA = A
sB = B
sC = C
sD = D
sE = E
sone = one
stwo = two
sthree = three
sfour = four
     StrSQL = "UPDATE pnl_results SET (" & sone & "," & stwo & "," & sthree & "," & sfour & ") Where  ('" & date =  sDate & "', '" & AA= sA & _
              "','" & BB= sB & "','" CC= & sC & "','" & DD= sD & "','" & EE=sE & ")"
     Set objRec = objConn.Execute(StrSQL)

objConn.Close
Set objConn = Nothing

End Sub

2 个答案:

答案 0 :(得分:3)

您的代码中存在多个错误:

  • 你不需要括号。
  • 将列名直接放在字符串中,不要用撇号包围它们。
  • 使用撇号包围所有字符串值。
  • 使用ANDOR运算符组合不同的条件,而不是逗号。

试试这个:

StrSQL = "UPDATE pnl_results SET " & _
         " one = '" & sone & _
         "', two = '" & stwo & _
         "', three = '" & sthree & _
         "', four = '" & sfour & _
         "' Where date = '" & sDate & _
         "' AND AA = '" & sA & _
         "' AND BB = '" & sB & _
         "' AND CC = '" & sC & _
         "' AND DD = '" & sD & _
         "' AND EE = '" & sE & "'"

正如评论中所提到的,使用直接来自用户输入的值的内联查询会使您的代码对SQL注入攻击开放。在查询中使用之前验证用户输入,或者更好地使用参数化查询。

答案 1 :(得分:1)

您在StrSQL = "UPDATE pnl_results SET field1='value1', field2='value2' WHERE field3='value3' AND field4='value4' 和{{1}}之间混淆了语法。看起来应该更像这样:

{{1}}