一尘不染

SQL语句中的全局变量

sql

我在VBA中有以下代码:

Dim strSQL As String
strSQL = "UPDATE Workstations SET MID = newvalue WHERE MID = tempvalue"
DoCmd.RunSQL strSQL

newvalue和tempvalue都是全局变量,并且已经被设置为值。语法上,这有意义吗?还是我缺少引号?


阅读 313

收藏
2021-05-05

共1个答案

一尘不染

试试这个:

如果MID数字

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = " & newvalue & " WHERE [MID] = " & tempvalue
DoCmd.RunSQL strSQL

IfMID字符串 (如果newvalue/tempvalue不包含单引号'):

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = '" & newvalue & "' WHERE [MID] = '" & tempvalue & "'"
DoCmd.RunSQL strSQL

IfMID字符串 (如果newvalue/tempvalue包含单引号,'newvalue="Mike's car"):

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = '" & Replace(newvalue, "'", "''") & "' WHERE [MID] = '" & Replace(tempvalue, "'", "''") & "'"
DoCmd.RunSQL strSQL

如果MID日期

Dim strSQL As String
strSQL = "UPDATE Workstations SET [MID] = #" & newvalue & "# WHERE [MID] = #" & tempvalue & "#"
DoCmd.RunSQL strSQL

感谢@HansUp在注释中指出,

MID是函数的名称,因此在SQL语句中将该字段名称放在方括号或别名中会更安全:SET [MID]

2021-05-05