我在VBA中有以下代码:
Dim strSQL As String strSQL = "UPDATE Workstations SET MID = newvalue WHERE MID = tempvalue" DoCmd.RunSQL strSQL
newvalue和tempvalue都是全局变量,并且已经被设置为值。语法上,这有意义吗?还是我缺少引号?
试试这个:
如果MID是 数字 :
MID
Dim strSQL As String strSQL = "UPDATE Workstations SET [MID] = " & newvalue & " WHERE [MID] = " & tempvalue DoCmd.RunSQL strSQL
IfMID是 字符串 (如果newvalue/tempvalue不包含单引号'):
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"):
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]