2013-01-24 63 views
2

我正在開發註冊系統。但我收到此錯誤:You tried to execute a query that does not include the specified expression..訪問MS ACESS時出錯

我使用下面的代碼:

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

回答

3

HAVING該子句引用這些2個字段:

  • tblTeacher.TeacherID
  • tblSection.SchoolYear

SELECT字段列表包括:

  • tblAdviser.TeacherID
  • tblAdviser.SchoolYear

更改查詢,以便於TeacherID所有引用來自同一個表。爲SchoolYear做同樣的事情。

順便說一句,tblTeacher甚至不包括在查詢的數據源中。

如果可能,請啓動Access會話並使用查詢設計器構建此查詢。它會幫助你避免這種類型的錯誤。一旦你有一個在Access中工作的查詢,然後調整你的代碼來產生相同的工作SQL語句。

+0

我可以只更改HAVING子句中的2個字段以匹配SELECT字段嗎? –

+0

這是我會嘗試的第一件事。當您在Access中嘗試將其作爲新查詢時會發生什麼? – HansUp

+0

謝謝!其工作已經完成。我欠你一輛車。 :) –

0

集團通過已經與一個集合函數中使用,因此您可以檢索組合的結果,但您尚未使用任何聚合函數。

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

刪除組從您的查詢和where子句中添加having子句。

說明您期待的數據類型,以便我們可以幫助您進行查詢。