我在下面的Sub
中编写了一些Make-table
查询,其中一些使用参数Some_date
Sub run_query(queryName As String, Optional Some_date As Date)
Form_Select_input.logProgress queryName
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs(queryName)
On Error Resume Next
qdf!Date_after = Date_after
On Error GoTo 0
qdf.Execute
Set qdf = Nothing
End Sub
一个典型的查询看起来像
PARAMETERS Some_date DateTime;
SELECT Some_field
, Other_field
INTO Some_Target
FROM Some_Source
LEFT JOIN Other_Source
ON Some_Source.key = Other_Source.key
where Some_Source.Transaction_Date > [Some_date];
现在这在我第一次运行查询时有效,但是第二次出现错误,表明表已经存在,所以我想写类似
Sub run_query(queryName As String, Optional Some_date As Date)
Form_Select_input.logProgress queryName
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs(queryName)
On Error Resume Next
DoCmd.DeleteObject acTable, qdf.Destination ' At first execution, the destination does not exist, but we resume next
qdf!Date_after = Date_after ' For some queries, the parameter does not exist, but we resume next
On Error GoTo 0
qdf.Execute
Set qdf = Nothing
End Sub
[请帮助我用存在的内容替换qdf.Destination
。
If DCount("[Name]", "MSysObjects", "[Name] = '" & tblName & "'") = 0 Then
'do stuff
End If
考虑此查询:
queryName = "typical_query"
? CurrentDb.QueryDefs(queryName).SQL
SELECT Year(i.OrderDate) AS [Year], Count(i.OrderID) AS TotalOrders
INTO Some_Target
FROM Invoice AS i
GROUP BY Year(i.OrderDate);
首先在Id
表中找到查询的MSysObjects
值:
queryId = DLookup("Id", "MSysObjects", "[Name]='" & queryName & "'") ? queryId -2147483409
然后找到MSysQueries
字段值为1的Id
(ObjectId
中的MSysQueries
)的Attribute
行。创建的表的名称存储在Name1
字段中:
? DLookup("Name1", "MSysQueries", "ObjectId=" & queryId & " AND [Attribute]=1") Some_Target
请谨慎使用系统表。您应该只阅读他们的数据是安全的。但是请避免修改数据,否则可能会破坏数据库。此方法要求您的Access用户具有对这些表的读取权限。如果您的数据库不允许他们读取权限,则可以执行
GRANT SELECT
语句将其授予他们。 (GRANT SELECT example)
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs(queryName)
dim strTarget as string
strTarget = trim(Split(Split(qdf.SQL, "INTO")(1), " ")(1))
On Error Resume Next
DoCmd.DeleteObject acTable, strTarget