【问题标题】:it gives an error when i run a SQL script当我运行 SQL 脚本时出现错误
【发布时间】:2023-01-25 18:47:25
【问题描述】:

我试图在 VBA 的表中使用 SQL INSERT INTO 但在运行此脚本时出现错误。为什么?

我原以为它会将值添加到表中,但它却给出了错误,有人对此有解决方案吗?

DoCmd.RunSQL "INSERT INTO tblScores (Student, Score, Date, ExamType, Lesson) VALUES (cbStudent.Value,txtScore.Value,txtDate.Value,cbExamType.value,cbLesson.Value);"

this is the error it gives

【问题讨论】:

    标签: sql vba ms-access syntax-error sql-insert


    【解决方案1】:

    表单值需要连接到 SQL 字符串,而不是包含在其中。

    例如:

    "WHERE ID =" & IdControl.Value
    

    但是由于种种原因不推荐这种方式。最好创建一个临时查询并将值作为参数传递。如果你需要经常运行它,创建一个永久查询并调用它——它会稍微快一些。

    Const SQL As String = "PARAMETERS [Student] Text (255), [Score] IEEESingle, [Date] DateTime, [ExamType] Text (255), [Lesson] Text (255); " & _
                          "INSERT INTO tblScores (Student, Score, [Date], ExamType, Lesson) " & _
                          "SELECT [Student] AS [Student], [Score] AS [Score], [Date] AS [Date], [ExamType] AS [ExamType], [Lesson] AS [Lesson];"
                          
    Dim q As DAO.QueryDef
    Set q = CurrentDb().CreateQueryDef("", SQL) 'temporary query 
        q.Parameters("[Student]").Value = cbStudent.Value
        q.Parameters("[Score]").Value = txtScore.Value
        q.Parameters("[Date]").Value = txtDate.Value
        q.Parameters("[ExamType]").Value = cbExamType.Value
        q.Parameters("[Lesson]").Value = cbLesson.Value
        q.Execute
        q.Close
    

    请记住,我不知道您的表字段的实际数据类型,因此某些参数可能会关闭 - 例如分数。

    【讨论】:

      最近更新 更多