2015-02-06 32 views
1

我有一張名爲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 

末次

+1

我不認爲這很重要,但嘗試改變插入到'INSERT INTO考試(Exam_Date,Student_Name)SELECT'。 Access可以使用insert ... select語句。 – jpw 2015-02-06 19:05:13

+0

謝謝jpw!我不明白爲什麼,但你的建議奏效! – user3657834 2015-02-06 19:43:13

回答

1

我知道你可能已經發現你的問題,但我確實想指出一些其他物品。

這是一個建立WHERE IN子句的非常有趣的設置。或者,你可能已經迭代的INSERT INTO ... VALUES的FOR/NEXT循環內:

INSERT INTO Exam (Exam_date, Student_Name) 
VALUES(#" & Me.ExamDate & "#, '" & Me.StudentListBox.ItemData(i) & "') 

還要檢查你的EXAM_DATE場。從你的查詢看起來你保留日期作爲一個字符串字段,但如果日期/時間字段,VBA查詢需要##而不是單引號。如果已經通過表單格式化爲這些日期類型,也不需要轉換函數CStr或CDate。

最後,對於數據庫設計建議,您應該在考試表內使用StudentID,而不是通過Full_Name將兩個表關聯起來:更好的索引,主鍵/外鍵參照完整性,數據存儲效率。另外,如果名稱有引號,則不需要轉義或拼寫錯誤,並且整數值在管理表之間的數據(即重複,查找)時更安全。