访问传递查询给出错误

时间:2012-01-25 17:40:29

标签: ms-access vba access-vba

我正在使用以下代码来运行直通查询。我正在尝试运行passthrough查询,然后检查返回的记录数以确定它是否有效。但我得到一个错误说

  

“无效操作”

为什么要这样做?我该如何纠正?

  Dim Item As String
  Item = InputBox("Enter Item needing a surrogate UPC.", "Enter Item")


Set db = CurrentDb

Set qdf = db.QueryDefs("spAL_AssignSurrogateUPC")
qdf.ReturnsRecords = True
qdf.SQL = "spAL_AssignSurrogateUPC '" & Item & "'"
With qdf.OpenRecordset(dbOpenSnapshot)       '<--- Error triggered here.
    If qdf.RecordCount = 1 Then
        MsgBox "Surrogate UPC assigned."
    Else
        MsgBox "ERROR.  Could not assign surrogate UPC."
    End If
End With

1 个答案:

答案 0 :(得分:1)

使用EXEC语法

qdf.SQL = "EXEC spAL_AssignSurrogateUPC '" & Replace(Item, "'", "''") & "';" 

(我假设它是SQL Server。)

我还添加了一个替换函数,以便处理Item字符串中的单引号。这也有助于防止SQL注入。


编辑:

尝试这样做,而不是使用With语句

Dim rs as DAO.Recordset

...

Set rs = qdf.OpenRecordset(dbOpenSnapshot)
If rs.EOF Then
    MsgBox "ERROR.  Could not assign surrogate UPC."
Else
    MsgBox "Surrogate UPC assigned."
End If