2017-06-08 16 views
1

VBAでSQL ServerデータベースからRecordsetにデータをプルしようとすると、Run-time error '-2147217900 (80040e14) Incorrect syntax new '11999999'が発生します。これはVBAを初めて使用しているため完全性が欠けています。VBAでSQLを実行すると実行時エラーが発生する

私のコードは以下の通りです。

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文で良く見えるbecuase好むよう複数行の文字列として格納されています。そのは、SQLクエリ(または2つの数字が同じであることをそのわずかcoincedence)に落ちるが、私は、私はSQL Serverでクエリを実行するときので、それを修正する方法について確認していないエラーから判断

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'" 

Management Studioがクエリを実行し、結果を返します(正確には21)。なぜVBAで実行しようとすると無効な構文エラーを返すのか混乱させるのですが、これはVBAでSQL文をフォーマットする不正な方法です?

答えて

4

ある数字とORキーワードの間に改行がありません。

and 11999999or call_id between 12000000 and 12999999or and 

は、文字列の各セクションの末尾にスペースを省略しないでください、および/またはキーワード

+0

私がスペースを忘れてしまったのは分かりません。 – WhatsThePoint

2

何をすべきかの一般的なヒント、あなたはVBAでSQLをデバッグする:

  1. は、テストのためのパブリックとしてBSMARTOpenFaultsを宣言する。
  2. 直下のウィンドウに移動して、?BSMARTOpenFaults
  3. 出力を参照してください。
  4. 出力を調べます。
  5. callwhereが1ワードであることを参照してください。
  6. 変更Const BSMARTOpenFaults = "select count(*) from call " _にコードので、言葉が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'" 
関連する問題