在VBA中执行SQL时出现运行时错误

时间:2017-06-08 10:08:25

标签: sql-server excel vba excel-vba

当我尝试将数据从SQL服务器数据库提取到VBA中的Recordset时,我得到Run-time error '-2147217900 (80040e14) Incorrect syntax new '11999999',这是我第一次使用VBA,因此原谅了缺乏完美。

我的代码如下;

Set connection = New ADODB.Connection
Dim newData As ADODB.Recordset

connection.ConnectionString = "my connection string" 'not posting this for security reasons'
connection.Open

Set newData = connectionExecute(BSMARTOpenFaults )

我将我的查询存储为多行字符串,因为我更喜欢它,因为它使用SQL语句看起来更好。

Private Const BSMARTOpenFaults = "select count(*) from call" _
& "where (" _
& "   call_id between 11000000 and 11999999" _
& "or call_id between 12000000 and 12999999" _
& "or call_id between 14000000 and 14999999" _
& "or call_id between 16000000 and 19999999" _
& "or call_id between 26000000 and 26999999" _
& "or call_id between 31000000 and 31999999" _
& "or call_id between 73000000 and 73999999)" _
& "and call_status <> 2 -- all open calls" _
& "and call_type = 'FT'"

判断错误它落在SQL查询上(或者它只是一个说明这两个数字是相同的),但我不确定如何解决它,因为当我在SQL Server Management Studio上运行查询时执行并返回一个结果(确切地说是21),因此在尝试使用VBA时,为什么它不会执行并返回无效的语法错误让我很困惑,这是在VBA中格式化SQL语句的错误方法吗?

3 个答案:

答案 0 :(得分:4)

数字和OR关键字之间没有换行符。您的陈述如下:

and 11999999or call_id between 12000000 and 12999999or and

在数字后面和/或关键字

之前添加空格

答案 1 :(得分:2)

一般提示在VBA中调试SQL时该怎么做:

  1. BSMARTOpenFaults声明为公开测试。
  2. 转到即时窗口并写下?BSMARTOpenFaults
  3. 查看输出。
  4. 检查输出。
  5. 看到callwhere只有一个字。
  6. 将代码更改为Const BSMARTOpenFaults = "select count(*) from call " _,因此单词为2。

答案 2 :(得分:2)

不要跳过字符串每个部分末尾的空格。在你的字符串返回时:

select count(*) from callwhere (...

callwhere可能不是您架构中的表格。 OR条款也存在同样的问题。试试这个:

Private Const BSMARTOpenFaults = "select count(*) from call " _
& "where (" _
& "   call_id between 11000000 and 11999999 " _
& "or call_id between 12000000 and 12999999 " _
& "or call_id between 14000000 and 14999999 " _
& "or call_id between 16000000 and 19999999 " _
& "or call_id between 26000000 and 26999999 " _
& "or call_id between 31000000 and 31999999 " _
& "or call_id between 73000000 and 73999999) " _
& "and call_status <> 2 " _
& "and call_type = 'FT'"