我有一張名爲Student的表格,其中包含學生的信息,例如他們的姓名。另一張表稱爲考試,考試時間爲考試日期,學生的姓名爲主鍵。我有一個表格可用於從列表框中選擇多個學生,然後將其插入選定日期的考試表格中。如何在Access VB中使用INSERT INTO SELECT查詢?
我相信我的語法是正確的,因爲如果我使用Access的查詢生成器並複製/粘貼我的SQL查詢並刪除表單內容,它將按預期工作。當我嘗試從VB運行它時得到的錯誤是Exam.Exam_Date是未知的,並檢查我的拼寫。我正在拼寫它在表格中的拼寫。
是不是可以在Access中使用INSERT INTO SELECT查詢?
這裏是我的代碼:
Private Sub add_Click()
Dim Students As String
Dim i As Integer
Dim dbs As DAO.Database
Dim SQL As String
SQL = ""
Students = "'"
For i = 0 To Me.StudentListBox.ListCount - 1
'check to see if students name is selected
If Me.StudentListBox.Selected(i) = True Then
'list student names in a string separated by commas
Students = Students + CStr(Me.StudentListBox.ItemData(i)) & "','"
End If
Next
If IsNull(Me.ExamDate) Then 'check if user entered an Exam date
MsgBox "Please select a date for the Exam."
ElseIf Students = "'" Then 'check if user selected ant Students
MsgBox "Please select Students to add to an Exam."
Else
'remove trailing comma
Students = Left(Students, Len(Students) - 2)
'sql query to add list of Students to an Exam on specified date
SQL = "INSERT INTO Exam (Exam.Exam_Date, Exam.Student_Name) SELECT '" & CDate(Me.ExamDate) & "', Students.Full_Name FROM Students WHERE Students.Full_Name IN (" & Students & ");"
DoCmd.RunSQL SQL
End If
末次
我不認爲這很重要,但嘗試改變插入到'INSERT INTO考試(Exam_Date,Student_Name)SELECT'。 Access可以使用insert ... select語句。 – jpw 2015-02-06 19:05:13
謝謝jpw!我不明白爲什麼,但你的建議奏效! – user3657834 2015-02-06 19:43:13