简体   繁体   中英

it gives an error when i run a SQL script

I'm trying to INSERT INTO with SQL in a table in VBA but it gives a error while running this script. why?

I was expecting it to add the values to the table but it gives an error instead, does anyone has the solution for this?

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

The error message:

这是它给出的错误

The form values need to be concatenated to the SQL string, not being enclosed to it.

For example:

"WHERE ID =" & IdControl.Value

But this way is not recommended for various reasons. Best to create a temporary query and pass the values as parameters. If you need to run it frequently, create a permanent query and just call it - it will be slightly faster.

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

Keep in mind I don't know the actual data-types of your table fields, so some of the params could be off - the score for example.

Try this: Dim varStudent as String. varStudent = cbStudent. In SQL String: VALUES ( '" & varStudent & "', '" & varTxtScore & "'

'" = SingleQuote DoubleQuote

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM