MS ACCESS访问时出错

时间:2013-01-24 04:50:32

标签: ms-access vb6

我正在开发一个注册系统。但我收到此错误:You tried to execute a query that does not include the specified expression..

我使用以下代码:

Private Function RefreshAdvisoryList()

    Dim vRS As New ADODB.Recordset
    Dim sSQL As String

    'clear list
    txtsection.Clear

    'On Error GoTo ReleaseAndExit

        sSQL = "SELECT tblSection.SectionID, tblSection.SectionTitle, tblAdviser.SchoolYear, tblDepartment.DepartmentTitle, tblYearLevel.YearLevelTitle, tblAdviser.TeacherID" & _
                " FROM (tblDepartment INNER JOIN (tblYearLevel INNER JOIN tblSection ON tblYearLevel.YearLevelID = tblSection.YearLevelID) ON tblDepartment.DepartmentID = tblSection.DepartmentID) INNER JOIN tblAdviser ON (tblSection.SectionID = tblAdviser.SectionID) AND (tblDepartment.DepartmentID = tblAdviser.DepartmentID)" & _
                " GROUP BY tblSection.SectionID, tblSection.SectionTitle, tblAdviser.SchoolYear, tblDepartment.DepartmentTitle, tblYearLevel.YearLevelTitle, tblAdviser.TeacherID" & _
                " HAVING (((tblTeacher.TeacherID)='" & curTeacher.TeacherID & "') AND tblSection.SchoolYear='" & Me.txtSchoolYear.Text & "')" & _
                " ORDER BY tblAdviser.SchoolYear DESC;"


    If ConnectRS(con, vRS, sSQL) = False Then
        'fatal
        'temp
        MsgBox "Unable to connect Teacher's Advisory Recordset.", vbCritical
        'GoTo ReleaseAndExit
    End If

    If AnyRecordExisted(vRS) = True Then
        While vRS.EOF = False
        txtsection.AddItem vRS!SectionTitle
        vRS.MoveNext
   Wend
    End If

'Exit Function
'ReleaseAndExit:
'    Set vRS = Nothing
End Function

看一下这个截图: enter image description here

2 个答案:

答案 0 :(得分:3)

HAVING子句引用这两个字段:

  • tblTeacher.TeacherID
  • tblSection.SchoolYear

SELECT字段列表包括:

  • tblAdviser.TeacherID
  • tblAdviser.SchoolYear

更改查询,以便对TeacherID的所有引用都来自同一个表。对SchoolYear执行相同的操作。

BTW,tblTeacher甚至不包括在查询的数据源中。

如果可能,启动Access会话并使用查询设计器构建此查询。它将帮助您避免此类错误。一旦您有一个在Access中工作的查询,然后调整您的代码以生成相同的工作SQL语句。

答案 1 :(得分:0)

Group by必须与聚合函数一起使用,以便可以检索组的组合结果,而您没有使用任何聚合函数。

参考 - http://www.w3schools.com/sql/sql_groupby.asp

从查询中删除group by,并在where子句中添加having子句。

说明您期望的数据类型,以便我们可以帮助您进行查询。