如何使用Excel VBA将开始日期和结束日期参数传递给SQL?

时间:2017-01-30 17:02:05

标签: sql sql-server excel-vba stored-procedures vba

当我从Excel单元格D2中的Northwind DB示例中输入客户ID时,我有以下代码(例如)ALFKI:

excel screen

这是我目前运行的Excel VBA代码:

CREATE PROCEDURE [dbo].[SP_GetOrdersForCustomer]
@CustomerID nchar(5)
AS
 BEGIN
    SELECT cst.[CustomerID],
    cst.[CompanyName],
    cst.[ContactName],
    ord.[OrderID],
    ord.[EmployeeID],
    emp.[FirstName],
    emp.[LastName],
    ord.[ShippedDate],
    prd.[ProductName],
    od.[UnitPrice],
    od.[Quantity]
       FROM [Customers] cst,
         [Orders] ord,
         [Order Details] od,
         [Employees] emp,
         [Products] prd
      WHERE ord.[CustomerID] = cst.[CustomerID]
    AND emp.[EmployeeID] = ord.[EmployeeID]
    AND od.[OrderID] = ord.[OrderID]
    AND prd.[ProductID] = od.[ProductID]
    AND cst.[CustomerID] = @CustomerID
     ORDER BY cst.[CustomerID], emp.[EmployeeID], ord.[ShippedDate] DESC
    END 

存储过程是SP_GetOrdersForCustomer,它是:

' Set up the parameter for our Stored Procedure
' (Parameter types can be adVarChar,adDate,adInteger,etc)
cmd.Parameters.Append cmd.CreateParameter("@Beginning_Date", adDate, adParamInput, 10, Range("F1").Text)
cmd.Parameters.Append cmd.CreateParameter("@Ending_Date", adDate, adParamInput, 10, Range("F2").Text)

我现在需要执行存储过程"按年销售"在Northwind中有两个日期参数@Beginning_Date和@Ending_Date都是datetime数据类型。

如果我将1996-07-01的日期放在Cell F1和1996-08-01的Cell F2中,那么请调用参数:

USE [Northwind]
GO
/****** Object:  StoredProcedure [dbo].[Sales by Year]    Script Date:   30/01/2017 22:04:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER procedure [dbo].[Sales by Year] 
@Beginning_Date DateTime, @Ending_Date DateTime AS
SELECT Orders.ShippedDate, Orders.OrderID, "Order Subtotals".Subtotal, DATENAME(yy,ShippedDate) AS Year
FROM Orders INNER JOIN "Order Subtotals" ON Orders.OrderID = "Order Subtotals".OrderID
WHERE Orders.ShippedDate Between @Beginning_Date And @Ending_Date

它不起作用。

这是包含日期的存储过程:

Sub Button1_Click()
Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim WSP1 As Worksheet
Set con = New ADODB.Connection
Set cmd = New ADODB.Command
Set rs = New ADODB.Recordset


Application.DisplayStatusBar = True
Application.StatusBar = "Contacting SQL Server..."

' Remove any values in the cells and clear a space where we want to dump and put our Stored Procedure's results.
Dim rngRange As Range
Set rngRange = Range(Cells(8, 2), Cells(Rows.Count, 1)).EntireRow
rngRange.ClearContents

' Log into our SQL Server, and run the Stored Procedure
con.Open "Provider=SQLOLEDB;Data Source=localhost;Initial Catalog=Northwind;Integrated Security=SSPI;Trusted_Connection=Yes;"
cmd.ActiveConnection = con


' Set up the parameter for our Stored Procedure
' (Parameter types can be adVarChar,adDate,adInteger,etc)
cmd.Parameters.Append cmd.CreateParameter("@Beginning_Date", adDate, adParamInput, 10, Range("J1").Text)
cmd.Parameters.Append cmd.CreateParameter("@Ending_Date", adDate, adParamInput, 10, Range("J2").Text)

'Show some text at the bottom on the status bar
Application.StatusBar = "Running stored procedure..."

'run the stored procedure name in SQL and drop the prefix dbo. it's not needed
cmd.CommandText = "Sales by Year"

'Execute it
Set rs = cmd.Execute(, , adCmdStoredProc)

' Copy the results to cell B7 on the first Worksheet
Set WSP1 = Worksheets(1)
WSP1.Activate
If rs.EOF = False Then WSP1.Cells(8, 2).CopyFromRecordset rs

'clean terminate
rs.Close
Set rs = Nothing
Set cmd = Nothing

'close off the connection to the SQL database
con.Close
Set con = Nothing

'Did it work ? Then display message at the bottom status bar
Application.StatusBar = "Data successfully updated."

End Sub

这是Excel VBA不起作用。我尝试修改上面显示的内容,我认为我应该使用adDBdate而不是adDate,但是它会失败并且#34;错误3421应用程序使用错误类型的值进行当前操作":

RecyclerViewAdapter

1 个答案:

答案 0 :(得分:0)

我有一个类似的问题,将用户在excel中输入的日期传递给SQL Server。我要做的是转换excel日期格式,这是今天2017-04-14由42839表示的地方。要将42839转换为SQL可以摄取我使用的日期格式(dateadd(d,42839,'1899-12-30) “))。

您可能会将Range(“J1”.text)传递为“42839”。