VBA SQL多个运行时错误

时间:2019-02-15 14:10:07

标签: sql excel vba

VBA使用下面显示的SQL select语句返回运行时错误。要解决此问题,我会在出现提示时一次删除一行,但这是大多数行。我得到的第一个错误是“运行时错误'-2147217900(80040E14)':

[Microsoft] [ODBC SQL Server驱动程序] [Sql Server]关键字“ by”附近的语法不正确。

在线进行一些挖掘,这可能是由于SQL脚本中的某些功能可能无法正常工作。我无法确认这一点。

与数据库的连接很好,我在VBA中将完全相同的代码用于没有错误运行的其他SQL脚本。另外,我可以从VBA中复制SQL语句并将其粘贴到SQL中并运行(显然,删除了VBA编码中的“和”&_表示法以及每一行的开头和结尾)。

Dim CnSQL As ADODB.Connection
Dim Server_Name As String
Dim Database_Name As String
Dim User_ID As String
Dim Password As String
Dim SQLStr As String
Dim COLOFFSET As Integer
Dim HF As Object
Dim RS As ADODB.Recordset 
Set RS = New ADODB.Recordset 
COLOFFSET = 1

Application.ScreenUpdating = False

   Server_Name = "xx.xxx.xx.xx"
   Database_Name = "xxxxxxxxxxxxxxxxxxxxx"
   User_ID = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"
   Password = "xxxxxxxxxxxxxxxxxxxxxxxxxxx"

Set CnSQL = New ADODB.Connection
CnSQL.CommandTimeout = 300

CnSQL.Open "Driver={SQL Server};Server=" & Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"

 Sql Statement
SQLStr = "select rdata2.description, Bin_Box_Locator, [Bin_Box_Level], LOC_CHECKER" & _
    ",Section, aisle, Bay, Level, Bin_Box_Level" & _
    ",SUM(convert(int,loc_checker)) over (partition by Bin_Box_Locator) as [Locs_Used]" & _
    ",sum(rdata2.Location_Cubes) as [Total_Location_Cubes]" & _
    "from" & _
    "(select s.description, iif(SUM(qty_available + qty_allocated + qty_quarantine + qty_damaged+ qty_hold) > 0,'1','0') AS [LOC_CHECKER]" & _
    ",iif(len(s.description)=14,left(s.description, len(s.description)-1),s.description) as [Bin_Box_Locator]" & _
    ",SUBSTRING(s.description,1,1) AS 'Section',SUBSTRING(s.description,3,3) AS 'Aisle',SUBSTRING(s.description,7,3) AS 'Bay'" & _
    ",SUBSTRING(s.description,11,3) AS 'Level',SUBSTRING(s.description,14,1) AS [Bin_Box_Level]" & _
    ",sum(((s.width * s.height * s.depth)/1728)) as [Location_Cubes]" & _
    "from dv_storage s" & _
    "left join dv_inventory inv on s.id = inv.storage_id and (qty_available > 0 or qty_allocated > 0 or qty_quarantine > 0 or qty_hold > 0 or qty_damaged > 0)" & _
    "where s.warehouse_id = 63" & _
    "and s.description like '%-%'" & _
    "and len(s.description)=14" & _
    " and s.enabled = 1" & _
    "group by s.description" & _
    ") as rdata2" & _
    "group by rdata2.description, Bin_Box_Locator, LOC_CHECKER, [Bin_Box_Level]" & _
    ",Section, aisle, Bay, Level, Bin_Box_Level" & _
    "order by description asc"


Set RS = New ADODB.Recordset
RS.Open SQLStr, CnSQL, adOpenStatic, adLockOptimistic


   Sheets("ALL LOCATION DATA").Select

   ActiveSheet.Cells(2, 1).CopyFromRecordset RS

     checks if data is blank
If ActiveSheet.Cells(2, 1).Value = "" Then
    MsgBox "No Data Was Avaliable In Date Range"
    Exit Sub
End If

RS.Close

Set RS = Nothing
Set CnSQL = Nothing

0 个答案:

没有答案