在循环中执行的许多更改都可以通过使用 SQL 中的更新或删除查询来更有效地完成。
下面的示例创建一个 QueryDef 对象来更新 Employees 表,然后运行查询。
Dim dbsNorthwind As DAO.Database
Dim qdfChangeTitles As DAO.QueryDef
Set dbsNorthwind = CurrentDb
Set qdfChangeTitles = dbsNorthwind.CreateQueryDef("")
qdfChangeTitles.SQL = "Update Employees SET Title = " & _
"'Account Executive' Where Title = " & _
"'Sales Representative'"
' 调用查询.
qdfChangeTitles.Execute dbFailOnError
您可以将本示例中的整个 SQL 字符串替换为存储的参数查询,在这种情况下,过程会提示用户输入参数值。 以下示例演示如何将上一个示例重写为存储参数查询。
Dim dbsNorthwind As DAO.Database
Dim qdfChangeTitles As DAO.QueryDef
Dim strSQLUpdate As String
Dim strOld As String
Dim strNew As String
Set dbsNorthwind = CurrentDb
strSQLUpdate = "PARAMETERS [Old Title] Text, [New Title] Text; " & _
"Update Employees SET Title = [New Title] Where " & _
"Title = [Old Title]"
' 创建未存储的 QueryDef 对象.
Set qdfChangeTitles = dbsNorthwind.CreateQueryDef("", strSQLUpdate)
' 提示旧标题.
strOld = InputBox("Enter old job title:")
' 提示新标题.
strNew = InputBox("Enter new job title:")
' 设置参数.
qdfChangeTitles.Parameters("Old Title") = strOld
qdfChangeTitles.Parameters("New Title") = strNew
'调用查询.
qdfChangeTitles.Execute