如何从VBA找出MS ACCESS中查询创建的表?

问题描述 投票:2回答:3

我在下面的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

vba ms-access access-vba
3个回答
0
投票
您可以查询系统表以查看对象是否存在。

If DCount("[Name]", "MSysObjects", "[Name] = '" & tblName & "'") = 0 Then 'do stuff End If


0
投票
Access系统表可以为您提供保存的make-table查询创建的表的名称。

考虑此查询:

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的IdObjectId中的MSysQueries)的Attribute行。创建的表的名称存储在Name1字段中:

? DLookup("Name1", "MSysQueries", "ObjectId=" & queryId & " AND [Attribute]=1") Some_Target

请谨慎使用系统表。您应该只阅读他们的数据是安全的。但是请避免修改数据,否则可能会破坏数据库。 

此方法要求您的Access用户具有对这些表的读取权限。如果您的数据库不允许他们读取权限,则可以执行GRANT SELECT语句将其授予他们。 (GRANT SELECT example


0
投票
要获取目标表,您可以在代码中使用它:

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

© www.soinside.com 2019 - 2024. All rights reserved.