SELECT 查询在转换为 VBA 时不起作用 - 无效的 SQL 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27421873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SELECT query does not work when converted to VBA - invalid SQL statement
提问by kajnwunda
I have been struggling with SQL statement when converted to VBA. Basically, I wish to add something to it before executing (which shouldn't be a problem). However, when I try to run it before changes, VBA does not recognize it as a valid SQL statement. Despite trying to add/remove brackets and any other special character, it still does not work. Please note, that it works perfectly when run as a query. Please see the string below:
转换为 VBA 时,我一直在为 SQL 语句苦苦挣扎。基本上,我希望在执行之前添加一些东西(这应该不是问题)。但是,当我尝试在更改之前运行它时,VBA 无法将其识别为有效的 SQL 语句。尽管尝试添加/删除括号和任何其他特殊字符,但它仍然不起作用。请注意,它在作为查询运行时完美运行。请看下面的字符串:
SQLstr = "SELECT SourceData.[Fiscal Year], SourceData.[Fiscal Quarter ID], " _
& "SourceData.[Transaction Date], SourceData.[Sales Order Number], SourceData.[Activated?], " _
& "SourceData.[Product ID], SourceData.[Bookings Quantity], SourceData.[Term Length], " _
& "SourceData.[Estimated Expiring Quarter], SourceData.[End Customer Company Name], " _
& "SourceData.[Sold To Company Name] " _
& "FROM SourceData, finalCust, finalPart " _
& "WHERE (((SourceData.[End Customer Company Name]) Like finalCust.[FinalList]) " _
& "And ((SourceData.[Sold To Company Name]) Like finalPart.[FinalList]))"
The code is 'pure' SQL into VBA, without any amendments but I don't want to mislead.
代码是 VBA 中的“纯”SQL,没有任何修改,但我不想误导。
Here's an error message:
这是一条错误消息:
Run-time error '2342':
A RunSQL action requires an argument consisting of an SQL statement.
Which I would consider as unreadable SQL statement for VBA.
我认为这是 VBA 不可读的 SQL 语句。
采纳答案by HansUp
That error message is misleading. The real problem is that DoCmd.RunSQL
is intended for "action" queries: UPDATE
; INSERT
; DELETE
; etc.
该错误消息具有误导性。真正的问题是,DoCmd.RunSQL
是为“行动”的查询:UPDATE
; INSERT
; DELETE
; 等等。
It will not accept a plain SELECT
query. For example, this simple SELECT
query gives me that same "A RunSQL action requires an argument consisting of an SQL statement"message from DoCmd.RunSQL
:
它不会接受简单的SELECT
查询。例如,这个简单的SELECT
查询给了我同样的“A RunSQL 操作需要一个由 SQL 语句组成的参数”消息,来自DoCmd.RunSQL
:
Dim SQLstr As String
SQLstr = "SELECT * FROM tblFoo;"
DoCmd.RunSQL SQLstr
However, DoCmd.RunSQL
executes this valid UPDATE
statement without error:
但是,DoCmd.RunSQL
执行此有效UPDATE
语句没有错误:
SQLstr = "UPDATE tblFoo SET long_text='bar' WHERE id=1;"
DoCmd.RunSQL SQLstr
You need a different method to use your SELECT
query. And the choice of method depends on what you want to do with the results returned by the query.
您需要一种不同的方法来使用您的SELECT
查询。方法的选择取决于您想对查询返回的结果做什么。