how to update a record in a table via a sql command within an IF statement

ε祈祈猫儿з 提交于 2020-01-16 09:21:19

问题


I'm trying to close out a record, where I have a True/False column inside a table. Code below, I keep getting a compile error expected end of statement. What am I missing? It will only be one record that is True at any given time.

If Me.butCompleteFlight.Value = True Then 
    UPDATE tblFlightRecords SET strWorkingRecord = FALSE WHERE strWorkingRecord = TRUE

回答1:


You can't mix SQL code and VBA code like that.
You can execute the update statement with the method DoCmd.RunSQL:

If Me.butCompleteFlight.Value = True Then 
    Dim SQL As String 
    SQL = "UPDATE tblFlightRecords SET strWorkingRecord = FALSE WHERE strWorkingRecord = TRUE"
    DoCmd.RunSQL SQL
End If



回答2:


Generally, in no application layer language (from Java to Python to VBA) can you submit an SQL query by itself on a separate line. SQL is a special-purpose, separate language compared to a general-purpose language. Hence, it is not recognized in app layers.

You must invoke the SQL statement with an interface or API object. In MS Access VBA, there are many ways to run action queries, some of which support parameterization.

DoCmd Interface

  1. DoCmd.OpenQuery (requires a saved query in advance)

  2. DoCmd.RunSQL (runs a string query)

DAO API

  1. QueryDef.Execute (requires a saved or temporary query and supports parameterization)

  2. Database.Execute (runs a string or saved query)

ADO API

  1. Connection.Execute (runs a string or stored query)

  2. Command.Execute (runs a string or stored query, supports parameterization)

Do note: VBA is not the only way to connect to MS Access databases. Java, Python, C#, and still others can as well but you must adhere to the chosen SQL API, module, or library. None of which allows SQL to be run by itself on a separate line.



来源:https://stackoverflow.com/questions/59492375/how-to-update-a-record-in-a-table-via-a-sql-command-within-an-if-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!