我正在尝试编写一个表单,将数据插入到单个数据库中的多个表中。
我知道你不能通过一个Insert into
语句来做到这一点所以我读到我应该创建一个transaction
并包含多个Insert语句。我继续在第二次插入声明中获得3134 run time error
。这是代码:
Private Sub cmdAdd_Click()
DBEngine.BeginTrans
CurrentDb.Execute "INSERT into Names(StudentId, FirstName, MiddleName, LastName) VALUES (" & Me.txtStudentId & ",'" & _
Me.txtFirstName & "','" & Me.txtMiddleName & "','" & Me.txtLastName & "')"
CurrentDb.Execute "INSERT into Homeroom(StudentId, Grade, Homeroom_Primary, Name-Homeroom_Primary_Teacher) " & _
"VALUES (" & Me.txtStudentId & ",'" & Me.txtGrade & "','" & Me.txtHomeroom & "','" & Me.txtTeacher & "')"
CurrentDb.Execute "INSERT into [Ridgeview Math](StudentId, ExportGrade, DateTaken, SS, PR) VALUES (" & _
Me.txtStudentId & ",'" & Me.txtGrade & "',#" & Me.txtMathdate & "#,'" & Me.txtMathSS & "','" & Me.txtMathPR & "')"
CurrentDb.Execute "INSERT into [Ridgeview Reading](StudentId, ExportGrade, DateTaken, RSS, RPR, RIRL) " & _
"VALUES (" & Me.txtStudentId & "','" & Me.txtGrade & "',#" & Me.txtReadingdate & "#,'" & Me.txtReadingSS & "','" & _
Me.txtReadingPR & "','" & Me.txtReadingIRL & "')"
CurrentDb.Execute "INSERT into CompassGroup(StudentId, CompassGroup) VALUES (" & Me.txtStudentId & _
"," & Me.txtCompassGroup & ")"
DBEngine.CommitTrans
End Sub
我是否对嵌套的Insert语句做错了什么?
这一切都与创建变量并输入数据的表单相关联。第一个Insert语句没有给我任何错误。如果您需要更多信息,请与我们联系。
答案 0 :(得分:2)
由于破折号,将字段名称 Name-Homeroom_Primary_Teacher 括起来。
我建议您使用字符串变量来保存语句文本,Debug.Print
字符串,然后使用Execute
。
Dim strInsert As String
strInsert = "INSERT into Homeroom(StudentId, Grade, Homeroom_Primary, [Name-Homeroom_Primary_Teacher]) " & _
"VALUES (" & Me.txtStudentId & ",'" & Me.txtGrade & "','" & Me.txtHomeroom & "','" & Me.txtTeacher & "')"
Debug.Print strInsert
CurrentDb.Execute strInsert, dbFailonerror
如果出现错误,您可以转到立即窗口( Ctrl + g )来检查语句文本。您可以复制该文本,在查询设计器中创建新查询,切换到SQL视图,粘贴文本,然后在那里测试语句。
此外,您正在使用的方法需要大量连接。您可以考虑的其他选项是:参数查询;将行添加到DAO Recordsets
。