【问题标题】:Change Access Query Type Dynamically in VBA from a Pass Through (ODBC) Query to a regular Select Query在 VBA 中将访问查询类型从传递 (ODBC) 查询动态更改为常规选择查询
【发布时间】:2016-11-23 18:42:25
【问题描述】:

我对动态使用 Microsoft Access 查询很感兴趣,有时作为使用 ODBC 的传递查询以访问远程 SQL Server,有时作为本地选择查询以访问同一 Access 数据库中的表。但是,QueryDef.Type 属性是只读的,我不知道如何更改它。

所以在代码中它看起来像:

Dim qd As DAO.QueryDef
Set qd = CurrentDB.QueryDefs("qrySubForm1")

'this line turns the qd.Type property to dbQSQLPassThrough automatically I believe
qd.Connect = "ODBC;--connectionstring--"  

qd.SQL = "Select * from SomeRemoteTable"

'populate the subform with the results of the Pass Through query
SubForm1.SourceObject = "Query.qrySubForm1" 

'Intent: change to regular select query.
qd.Type = dbQSelect   ' Error: read-only property

qd.SQL = "Select * from ALocalTable"

' now change the SubForm to show results of the local query
SubForm1.SourceObject = "Query.qrySubForm1"  

QueryDef Type 属性是this 枚举中的值之一。

如果我在两个本地查询之间切换,或者在两个直通查询之间切换,它工作正常。只有当我尝试在直通查询和本地查询之间切换时才会遇到问题。

更新: This 对另一个 SO 问题的回答似乎表明我可以在查询定义中添加一个属性,但我不确定这是否适用于“类型”的情况。

【问题讨论】:

  • 就其本质而言,直通查询具有 ODBC 连接。这不是本地查询所必需的,因为您可以简单地执行 SQL。为什么不直接获取 SQL(例如:currentdb.querydefs("passthru").SQL)然后执行(但不使用之前的连接)?
  • 如果两个查询具有不同的 SQL(如您的代码所示),我将保留两个查询。并且只切换SubForm1.SourceObject

标签: ms-access vba ms-access-2013


【解决方案1】:

正确的方法是删除并创建QueryDef。

在更改为本地表之前添加:

DoCmd.DeleteObject acQuery, qd.name
Set qd= MyDB.CreateQueryDef(qd.name)
qd.SQL = "Select * from ALocalTable;"
qd.close

如果你想返回直通:

DoCmd.DeleteObject acQuery, qd.name
Set qd= MyDB.CreateQueryDef(qd.name)
qd.connect = GET_CONNECTION_STRING
qd.SQL = "Select * from SomeRemoteTable;"
qd.close

对于更新查询设置“qd.ReturnsRecords = false”

【讨论】:

  • 下周我才能确认这是否有效,但从逻辑上讲,我认为它会正常工作。我不认为只是清除查询定义并重新创建它。谢谢!
猜你喜欢
  • 1970-01-01
  • 2017-11-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-11-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多