Dim varCity As String
varCity = Me.txtDestinationCity
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE" & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"
我正在尝试选择所选城市的州。有一个带有城市列表的下拉框。该方框标题为txtDestinationCity
。
它说我的FROM子句中有错误。
谢谢
答案 0 :(得分:1)
你错过了一个空格和一些引用。怎么样:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE '" & Me.txtDestinationCity & "' = [TDestinationType].[tPreTravelDestinationCity]"
复制原件旁边的内容以查看差异。
由于SQL的原因,请转发比较。始终提到左栏和右栏:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = '" & Me.txtDestinationCity & "'"
由于引号很烦人且很容易错过,我建议定义一个这样的函数:
Public Function q(ByVal s As String) As String
q = "'" & s & "'"
End Function
然后编写类似的SQL字符串:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(Me.txtDestinationCity)
这可以确保您始终在正确的位置获得两个引号,而不会被双单双引号序列混淆。
如果您关心SQL注入(是的,请查看),请使用最小值
Public Function escapeSQL(sql As String) As String
escapeSQL = Replace(sql, "'", "''")
End Function
并在将用户输入连接到SQL子句的所有地方使用它,如下所示:
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
最后,为了便于阅读,请将其分解。我怀疑你的编辑器显示了200个字符宽:
Me.txtDestinationState.RowSource = _
"SELECT tPreTravelDestinationState " & _
"FROM [TDestinationType] " & _
"WHERE [TDestinationType].[tPreTravelDestinationCity] = " & q(escapeSQL(Me.txtDestinationCity))
注意每行的尾随空格!没有它们,连接将不起作用。
答案 1 :(得分:0)
如果首先将其设置为变量(例如,strSQL),则可以更轻松地对查询构造进行故障排除。然后你可以放一个断点并在它执行之前看到它。
答案 2 :(得分:-1)
你在WHERE之后需要一个空格。将WHERE"
更改为WHERE<space>"
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE " & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"