SQL语句中的全局变量

时间:2014-03-21 16:11:18

标签: sql vba ms-access access-vba

我在VBA中有以下代码:

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

newvalue和tempvalue都是全局变量,并且已经设置了值。语法明智,这有意义吗?还是我错过了引号?

1 个答案:

答案 0 :(得分:9)

试试这个:

如果MID 数字

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

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

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

如果MID字符串(如果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 date

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

感谢@HansUp在评论中指出,

  

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