我遇到了VBA SQL JOIN的麻烦。我继续得到A"加入表达不受支持"错误。以下代码在查询设计视图中工作,但在vba中似乎抛出错误。
Dim Rs As DAO.RecordSet
Set Rs = CurrentDb.OpenRecordset( _
"SELECT Schools.ID, Schools.[School Name],Schools.Address, Schools.Postcode, Schools.[Principal name], " & _
"Schools.[E-Mail], Schools.Phone, Schools.Region, Schools.JTHE, Schools.[Social Status], Events.Program " & _
"FROM Schools INNER JOIN Events ON Schools.ID = Events.School WHERE ((Schools.Region = '" & RegionOne & _
"' Or Schools.Region = '" & RegionTwo "' Or Schools.Region = '" & RegionThree "' Or Schools.Region = '" & _
RegionFour "') AND (Schools.JTHE = " & JTHE1 & " Or Schools.JTHE = " & JTHE2 ") AND (Schools.[Social Status] = '" & _
StatusBox.Value "') AND (Events.Program = '" & ProgramBox.Value & "'));")
此类似查询工作
Set Rs = CurrentDb.OpenRecordset("SELECT * FROM Schools WHERE " & _
"(((Schools.Region)='" & RegionOne & _
"' Or (Schools.Region)='" & RegionTwo & _
"' Or (Schools.Region)='" & RegionThree & _
"' Or (Schools.Region)='" & RegionFour & _
"') AND ((Schools.[Social Status])='" & StatusBox.Value & _
"') AND ((Schools.JTHE)=" & JTHE1 & " Or (Schools.JTHE)=" & JTHE2 & "));")
非常感谢任何帮助。
答案 0 :(得分:0)
我不完全确定为什么会这样。在VBA上执行此操作时很难发现错误,这与您在实际的SQL Management工作室中可以发现错误的行不同。尽管如此,你可以试试这个:
Set Rs = CurrentDb.OpenRecordset( _
"SELECT Schools.ID, Schools.[School Name], Schools.Address, " & _
"Schools.Postcode, Schools.[Principal name], Schools.[E-Mail], " & _
"Schools.Phone, Schools.Region, Schools.JTHE, Schools.[Social Status], " & _
"Events.Program " & _
"FROM Schools " & _
"INNER JOIN Events " & _
"ON Schools.ID = Events.School " & _
"WHERE Schools.Region IN (" & _
"'" & RegionOne & "'," & _
"'" & RegionTwo & "'," & _
"'" & RegionThree & "'," & _
"'" & RegionFour & "') " & _
"AND Schools.JTHE IN (" & JTHE1 & ", " & JTHE2 & ") " & _
"AND Schools.[Social Status]='" & StatusBox.Value & "' " & _
"AND Events.Program='" & ProgramBox.Value & "';")
我将其格式化,以便为您提供查询的故事(这就是我将如何在SQL中编写它)。
对您的问题不是直接回答,但我简化了您的OR
语句,而是使用IN
。你可能会得到:
连续线路错误太多
因此调整字符串的连接。我当然没有对此进行过测试(虽然它可以编译),但我的目标是让您了解可行的方法。 HTH。