1

我正在尝试编写一个表单来将数据插入到单个数据库中的多个表中。

我知道你不能通过单个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 语句没有给我任何错误。如果您需要更多信息,请告诉我。

4

1 回答 1

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.

于 2013-11-07T17:05:16.220 回答