gpt4 book ai didi

vba - 如何从 VBA 中找出 MS ACCESS 中的查询创建了哪个表?

转载 作者:行者123 更新时间:2023-12-04 10:24:41 26 4
gpt4 key购买 nike

我在下面写了 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与存在的东西。

最佳答案

Access 系统表可以为您提供已保存的生成表查询创建的表的名称。

考虑这个查询:

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 中的值 table :

queryId = DLookup("Id", "MSysObjects", "[Name]='" & queryName & "'")
? queryId
-2147483409

然后找到 MSysQueries该行 Id ( ObjectIdMSysQueries 中)其中 Attribute字段值为1。创建的表的名称存储在 Name1中。 field :

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

小心使用系统表。您应该安全地只读取他们的数据。但要避免修改数据,否则可能会破坏数据库。

此方法要求您的 Access 用户对这些表具有读取权限。如果你的数据库不允许他们读权限,你可以执行一个 GRANT SELECT声明给他们。 ( GRANT SELECT example )

关于vba - 如何从 VBA 中找出 MS ACCESS 中的查询创建了哪个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60672017/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com