2016-12-07 79 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