2016-12-07 81 views
0

我使用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 !!), - 没有任何反应。

但有时我可以在开发环境中看到数据库,查询在第一次运行时消失,代码崩溃当然。

任何想法,为什么发生这种情况,以及如何避免它?似乎删除和附属物一直无法正常工作。

感谢 迈克尔

+0

当代码失败时,它执行了这行'MsgBox Err.Description'? –

+0

不,因为我停用了msgbox。但没有错误处理程序它指向“如果不是IsNull(CurrentDb.QueryDefs(QueryName).Name)然后”与运行时错误3265 - 在此集合中找不到项目,我找不到任何不正确的代码。但我会尝试使用“On Error resume next”,也许它会跳过... – mak

+0

我已经添加了一般VBA标签,以增加对此问题的意见。 –

回答

0

不能检查查询对象是否存在这样的:

IsNull(CurrentDb.QueryDefs(QueryName).Name) 

它会立刻产生一个错误。您将不得不循环QueryDefs集合以查看名称是否存在。

但为什么要删除并创建查询?只需创建一次,然后在运行之前调整SQL。

+0

我没有准备好我的修改,但我认为你的想法是正确的。没有错误处理程序,我确切地看到这个代码“IsNull(CurrentDb.QueryDefs(QueryName).Name)”错误,我甚至不能用“On error resume next”跳过它。 – mak

0

如果有人有趣的是,这里是我的修改功能,希望能避免我的数据库中永久存储的查询的缺失:

Function SQL_PT(ByVal SQL As String, Optional QueryName As String) Dim qdf As QueryDef 

On Error GoTo ErrHandler 

If Len(QueryName) = 0 Then 'temp query  
    Set qdf = CurrentDb.CreateQueryDef("") 
    With qdf 
     .Connect = TempVars!ConnectionString 
     .SQL = SQL 
     .ReturnsRecords = False 
     .Execute 
    End With 

Else 
    Set qdf = CurrentDb.QueryDefs(QueryName) 
    qdf.SQL = SQL 
End If 

qdf.Close 
Set qdf = Nothing 

ExitHere: 
    Exit Function 

ErrHandler: 
MsgBox Err.Description 

    Resume ExitHere 
End Function 

我不删除并再重新创建查询,但只能修改查询的SQL。

Michael