VBA如何将DATE作为参数传递给存储过程

时间:2013-12-05 15:56:15

标签: excel vba excel-vba

目前我将date参数作为varchar和convert传递,因为我在传递date参数时遇到错误。我仍然得到错误,但它是一个转换参数。

Sub GetPositions() 'xdate As Date
Dim sSQL As String
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Set cmd = New ADODB.Command
Set prm = New ADODB.Parameter



Sheets("Positions").Select
Range("a2:bb999999").ClearContents
Set cn = New ADODB.Connection
cn.CommandTimeout = 300000
cn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial     Catalog=GlobalR;Data Source=SWP"

    Dim d As Date
    d = "2013/12/03"

    cmd.ActiveConnection = cn
    cmd.CommandType = adCmdStoredProc
    cmd.CommandText = "Get9599Delta"
    cmd.NamedParameters = True
    Set prm = cmd.CreateParameter("@date", adVarChar, adParamInput, 12)
    cmd.Parameters.Append prm
    cmd.Parameters("@date").Value = "'12/3/2013'"
    Set rs = New ADODB.Recordset
    rs.Open cmd.Execute ''''I AM GETTING AN ERROR ON THIS LINE THAT READS
     ''''''''''' CONVERSION FAILED WHEN CONVERTING DATETIME TO CHARACTER STRING

Cells(2, 1).CopyFromRecordset rs

rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing

End Sub

这是我的存储过程

alter PROC Get9599Delta (@date varchar(12))
AS
DECLARE @d DATETIME
SET @d = CONVERT(DateTime, @date, 104) --convert the varchar to a date

我知道为什么会遇到这种转换问题?

3 个答案:

答案 0 :(得分:0)

我正在使用Excel 2016 MSO(16.0.8730.2175)64位,而我的“VBAProject”正在引用“Microsoft ActiveX Data Objects 6.1 Library”。我正在运行SQL Server Express(64位)版本11.0.3156.0(2012)。

我的SQL Server数据库存储过程的日期参数带有datetime数据类型。存储过程包含SET NOCOUNT ON

这是我的代码的编辑版本:

Sub ExecuteStoredProcedure(date_ As Date)
    Dim connection_ As New ADODB.Connection
    connection_.Open "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;Initial Catalog=not_my_real_database_name;Integrated Security=SSPI"
    Dim command_ As New ADODB.Command

    With command_
        .ActiveConnection = connection_
        .CommandType = adCmdStoredProc
        .CommandText = "dbo.NotMyRealProcedureName"
        .Parameters.Append .CreateParameter("@Date", adDBDate, adParamInput, , date_)
        .Execute
    End With
End Sub

如果您遇到类似问题,请在connection_.Open ...电话后尝试评论或删除所有代码。我肯定有问题,因为传递给该调用的连接字符串和VBA显示的错误信息是如此之小,以至于我的问题与我的VBA代码中的日期参数无关,并不是很明显。

答案 1 :(得分:-1)

通过将SET NOCOUNT ON放在我的存储过程的顶部来解决问题!

答案 2 :(得分:-2)

试试这个:

.Parameters.Append .CreateParameter("@date", adDate, adParamInput, , )

@是可选的 msdn ( command.CreateParameter (Name, Type, Direction, Size, Value) )

和参数类型adDBTimeStamp