我使用PT查询从SQL Server 2008R2获取数据。 与ODBC连接字符串的查询存储在MS Access Client,从这个功能,我发现很久以前在网上获取变量SQL字符串:MS Access 2010:删除传递查询
'If QueryName is not provided or is an empty string (= "") no query object will be created but the SQL statement or stored procedure will be executed (useful for DELETE, INSERT, UPDATE statements).
'If you provide the parameter QueryName a query will be created with the provided name (this is useful for a SELECT statement as you expect to retrieve the resulting data set).
Function SQL_PassThrough(ByVal SQL As String, Optional QueryName As String)
Dim qdf As QueryDef
On Error GoTo ErrHandler
Set qdf = CurrentDb.CreateQueryDef
With qdf
.Name = QueryName
.Connect = TempVars!ConnectionString
.SQL = SQL
.ReturnsRecords = (Len(QueryName) > 0)
If .ReturnsRecords = False Then
.Execute
Else
If Not IsNull(CurrentDb.QueryDefs(QueryName).Name) Then
CurrentDb.QueryDefs.Delete QueryName
End If
CurrentDb.QueryDefs.Append qdf
End If
.Close
End With
Set qdf = Nothing
ExitHere:
Exit Function
ErrHandler:
MsgBox Err.Description
Resume ExitHere
End Function
TempVars的ConnectionString中包含的连接字符串,其存储在一个表中。
一切正常,而SQL字符串(例如“EXEC dbo.spLookupSomething”)返回0记录。
时不时 - 我找不到什么时候或为什么--PT查询根本就是从Access对象中删除的,并且不再被追加。 我注意到,该功能与
Set qdf = CurrentDb.CreateQueryDef
开始虽然有确切的该名称的查询已经存在。但在大多数情况下,它的工作原理似乎都覆盖了现有的查询,但有时根本不起作用。
我开始我所有的PT查询从这样的代码:
strsql=""EXEC dbo.spLookupSomething"
call SQL_PassThrough(strsql, "PT_LookupSomething")
它甚至很难复制这种行为。我试着多次运行代码(知道它返回0 !!), - 没有任何反应。
但有时我可以在开发环境中看到数据库,查询在第一次运行时消失,代码崩溃当然。
任何想法,为什么发生这种情况,以及如何避免它?似乎删除和附属物一直无法正常工作。
感谢 迈克尔
当代码失败时,它执行了这行'MsgBox Err.Description'? –
不,因为我停用了msgbox。但没有错误处理程序它指向“如果不是IsNull(CurrentDb.QueryDefs(QueryName).Name)然后”与运行时错误3265 - 在此集合中找不到项目,我找不到任何不正确的代码。但我会尝试使用“On Error resume next”,也许它会跳过... – mak
我已经添加了一般VBA标签,以增加对此问题的意见。 –