针对 ODBC 外部数据库的生成表查询将具有.SQL
与此类似的属性
SELECT localTable.ID, localTable.textCol
INTO (ODBC;DSN=myDb;Trusted_Connection=Yes;DATABASE=myDb;AutoTranslate=No;) externalTable
FROM localTable;
因此,我们可以使用一些 VBA 代码来识别该类型的生成表查询,将表放到 SQL Server 上,然后执行生成表查询。所以,而不是做
DoCmd.OpenQuery "YourMakeTableQueryName"
(正如我现在怀疑代码所做的那样)你可以使用
RunMakeTableQuery "YourMakeTableQueryName"
其中RunMakeTableQuery
在标准 VBA 模块中定义为
Option Compare Database
Option Explicit
Public Sub RunMakeTableQuery(MakeTableQueryName As String)
Dim cdb As DAO.Database, qdf As DAO.QueryDef, qdf2 As DAO.QueryDef
Dim i As Long, j As Long, ConnectionString As String, TableName As String
Const ExternalIntoTag = "INTO (ODBC;"
Set cdb = CurrentDb
Set qdf = cdb.QueryDefs(MakeTableQueryName)
i = InStr(1, qdf.SQL, ExternalIntoTag, vbBinaryCompare)
If i > 0 Then
' target table is external (SQL Server)
i = i + Len(ExternalIntoTag)
j = InStr(i, qdf.SQL, ")", vbBinaryCompare)
ConnectionString = Trim(Mid(qdf.SQL, i, j - i))
i = InStr(j + 1, qdf.SQL, "FROM", vbBinaryCompare)
TableName = Trim(Mid(qdf.SQL, j + 1, i - j - 3))
Set qdf2 = cdb.CreateQueryDef("")
qdf2.Connect = "ODBC;" + ConnectionString
qdf2.ReturnsRecords = False
qdf2.SQL = "IF OBJECT_ID('" & TableName & "','U') IS NOT NULL DROP TABLE [" & TableName & "]"
qdf2.Execute dbFailOnError
Set qdf2 = Nothing
qdf.Execute dbFailOnError
Set qdf = Nothing
Else
' target table is an Access table
Set qdf = Nothing
' this will overwrite an existing target table with no prompts
DoCmd.SetWarnings False
DoCmd.OpenQuery MakeTableQueryName
DoCmd.SetWarnings True
End If
Set cdb = Nothing
End Sub