我正在连接到Visual Basic中的数据库。连接后,我想运行以下查询并将结果输出到电子表格。当我在Access中运行查询时,查询给了我预期的结果。但是,我不知道如何将查询转换为VB语法。
谁能告诉我此SQL语句有什么问题,或者为什么我收到错误消息,指出我的SQL语句中有保留字?
Dim SQL As String
Dim numrows As Integer
Range("B1").Value = CustFirstName & CustLastName
SQL = "SELECT Orders.OrderDate, Sum(QuotedPrice*QuantityOrdered) AS TotalCost" _
& "FROM Orders INNER JOIN LineItems ON Orders.OrderID = LineItems.OrderID" _
& "WHERE (((Orders.customerID) = [Customer].[customerID]))" _
& "GROUP BY Orders.OrderID, Orders.OrderDate" _
& "ORDER BY Orders.OrderDate"
答案 0 :(得分:2)
您的SQL字符串错误。它缺少FROM子句,并且WHERE,GROUP BY,ORDER BY都写错了。这些关键字之前至少应有一个空格,但是您会遇到类似这样的情况:
SQL = "... TotalCost" & "FROM ..."
将其设置为“ .... TotalCostFROM ...”。与WHERE,GROUP BY,ORDER BY相同。尝试将其重写为:
SQL = "SELECT Orders.OrderDate, Sum(QuotedPrice*QuantityOrdered) AS TotalCost" _
& " FROM Orders INNER JOIN LineItems ON Orders.OrderID = LineItems.OrderID" _
& " GROUP BY Orders.OrderID, Orders.OrderDate" _
& " ORDER BY Orders.OrderDate"
我还删除了WHERE部分,因为它包含不存在的[Customer]。[customerID]。
请注意结果,您将按OrderId然后按OrderDate分组。结果可能在同一日期有多个条目(不同的ID)。
答案 1 :(得分:1)
在每个续行的开头或结尾缺少分隔符空间的情况下,WHERE子句不正确。变量输入必须串联在一起。表单字段/控件的引用是变量输入。
SQL = "SELECT Orders.OrderDate, Sum(QuotedPrice*QuantityOrdered) AS TotalCost " _
& "FROM Orders INNER JOIN LineItems ON Orders.OrderID = LineItems.OrderID " _
& "WHERE Orders.customerID = " & Me.customerID & " " _
& "GROUP BY Orders.OrderID, Orders.OrderDate " _
& "ORDER BY Orders.OrderDate"
如果需要考虑SQL注入,请使用PARAMETERS而不是串联。 How does the SQL injection from the "Bobby Tables" XKCD comic work?