简体   繁体   English

为什么 ms-access sql Pass Through 在 VBA 中不起作用

[英]Why does an ms-access sql Pass Through not work in VBA

I am currently trying to write a select pass through query using VBA in Access 2016. If I use the manual option via the button Pass-Through and assign manually the dsn the following statement works.我目前正在尝试使用 Access 2016 中的 VBA 编写 select 通过查询。如果我通过按钮 Pass-Through 使用手动选项并手动分配 dsn,则以下语句有效。
手动通过

SELECT top 1 dat_Kunden.Kunden_Status FROM dat_Kunden

The sql I want to pass through is changing so I want to create a VBA Function to execute it.我想通过的 sql 正在改变,所以我想创建一个 VBA Function 来执行它。

This is my current Function to execute a given sql statement这是我当前的 Function 执行给定的 sql 语句

Function CreateSPT(strSQL As String)

Dim qdf As DAO.QueryDef, rs As DAO.Recordset
Set qdf = CurrentDb.CreateQueryDef("")
qdf.Connect = "ODBC;Driver=SQL Server;SERVER=xxx;DATABASE=yyy;UID=zzz"    'in the code this is the real data
qdf.SQL = strSQL
qdf.ReturnsRecords = True

Set rs = qdf.OpenRecordset()
If Not (rs.BOF And rs.EOF) Then rs.MoveFirst
    Do Until rs.EOF
        Debug.Print rs.Fields(0)
        rs.MoveNext
    Loop


rs.Close
Set rs = Nothing
Set qdf = Nothing

End Function

This does work.这确实有效。

Sub test_sql()
SQL = "SELECT CONVERT( date, GETDATE() ) AS qryTest"
CreateSPT (SQL)
End Sub

This statement which works via the manual pass through does not work这个通过手动传递的语句不起作用

Sub test_sql2()
SQL =  "SELECT top 1 dat_Kunden.Kunden_Status FROM dat_Kunden  AS qryTest"
CreateSPT (SQL)
End Sub

The Error code is Run-time error '3146': ODBC -- call failed at this line:错误代码是 Run-time error '3146': ODBC -- call failed at this line:

Set rs = qdf.OpenRecordset()

I hope you have an idea where my mistake is... Thanks to all of you, learned a lot from you!我希望你知道我的错误在哪里......感谢你们所有人,从你们那里学到了很多!

If you provide an alias , use it:如果您提供别名,请使用它:

SQL = "SELECT Top 1 qryTest.Kunden_Status FROM dat_Kunden AS qryTest"

or ignore it:或忽略它:

SQL = "SELECT Top 1 Kunden_Status FROM dat_Kunden AS qryTest"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM