从SQL到Access链接表问题 - ODBC失败

时间:2015-08-18 06:32:27

标签: sql vba ms-access access-vba odbc

我在MS访问中开发表单。我使用SELECT函数将数据加载到表单。当我创建一个SQL链接表(外部数据,ODBC数据库..)时,我收到错误' 3146 ODBC - 调用失败'。但是当我导入没有SQL链接的表时,它可以工作。

其他选择功能适用于链接表格。

    Dim rs As Recordset
    Dim rs_Change_Control As Recordset

    CustId = Me.txt_ID.Value
    If Len(CustId) > 0 Then

       Set rs = CurrentDb.OpenRecordset("SELECT a.key, a.date 
        FROM (SELECT gnr.key, gnr.date
            FROM gnr) a 
                INNER JOIN (SELECT key, MAX(date) AS maxtime 
                FROM gnr GROUP BY key) b 
            ON a.key = b.key AND a.date = b.maxtime WHERE a.key = '123456789';")
If rs.EOF = False Then
Me.txt_ID.Value = rs!key
    End if

2 个答案:

答案 0 :(得分:0)

您需要更正查询中的引号,

Set rs = CurrentDb.OpenRecordset(SELECT a.key, a.date 
    FROM ("SELECT gnr.key, gnr.date
        FROM gnr) a 
            INNER JOIN (SELECT key, MAX(date) AS maxtime 
            FROM gnr GROUP BY key) b 
        ON a.key = b.key AND a.date = b.maxtime WHERE a.key = '123456789'";)

应该是

 Set rs = CurrentDb.OpenRecordset("SELECT a.key, a.date 
    FROM (SELECT gnr.key, gnr.date
        FROM gnr) a 
            INNER JOIN (SELECT key, MAX(date) AS maxtime 
            FROM gnr GROUP BY key) b 
        ON a.key = b.key AND a.date = b.maxtime WHERE a.key = '123456789'")

答案 1 :(得分:0)

这可能是也可能不是问题,但date是保留字 尝试将其括在方括号中:a.[date]MAX([date])等,无论它出现在哪里。

如果可能,请重命名该列。它会一次又一次地产生问题。