Dim varCity As String
varCity = Me.txtDestinationCity
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE" & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"
我正在尝试选择所选城市的州。有一个带有城市列表的下拉框。那个盒子的标题是txtDestinationCity
。
它说我的FROM子句有错误。
谢谢
你错过了一个空间和一些报价。怎么样:
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))
注意每行的尾随空格!没有它们,连接将不起作用。
如果首先将其设置为变量(例如,strSQL),则可以更轻松地对查询构造进行故障排除。然后你可以放一个断点并在它执行之前看到它。
在WHERE之后你需要一个空格。将WHERE"
改为WHERE<space>"
Me.txtDestinationState.RowSource = "SELECT tPreTravelDestinationState FROM [TDestinationType] WHERE " & Me.txtDestinationCity & "= [TDestinationType].[tPreTravelDestinationCity]"