VBA:使用两个参数调用SQL Server存储过程

时间:2014-10-07 07:09:45

标签: sql excel vba arguments

如标题中所述,我只想从VBA调用SQL Server存储过程。

我可以像这样调用我的存储过程:

  EXEC  dbo.spClientXLS @Nr =  ' 131783', @date = '21.09.2014'

NrvarChar(50)类型值,date类型为date

现在,如果我想从VBA调用它,我会收到一条错误消息。我在VBA中的代码是:

...'SQL Server stored procedure which is to execute with parameters
Dim ADODBCmd As New ADODB.Command
With ADODBCmd
    .ActiveConnection = objconn
    .CommandTimeout = 500
    .CommandText = "dbo.spClient"
    .CommandType = adCmdStoredProc
End With
Set recordset = ADODBCmd.Execute(, date, Nr)

Date的类型为DateNr的类型为String

我很高兴,如果有人能解释我,我怎么能用两个论点来处理它。

此致

2 个答案:

答案 0 :(得分:5)

试试这个。

Dim cmd As New ADODB.Command
Dim rs As ADODB.Recordset

With cmd
    .ActiveConnection = objcnn
    .CommandText = "spClient"
    .CommandType = adCmdStoredProc
    .Parameters.Refresh
    If .Parameters.Count = 0 Then
        .Parameters.Append cmd.CreateParameter("@Nr", adVarChar, adParamInput, 50)
        .Parameters.Append cmd.CreateParameter("@date", adDate, adParamInput)
    End If
    .Parameters.Item("@Nr").Value = "131783"
    .Parameters.Item("@date").Value = "09/21/2014"
    Set rs = .Execute()

End With

答案 1 :(得分:0)

您需要在代码中添加命令参数以接受参数值。检查以下代码:

    Set oConn = New ADODB.Connection
    Set rs = New ADODB.Recordset
    Set cmd = New ADODB.Command

    oConn.Open strConn  '' strConn will have your connection string

    stProcName = "thenameofmystoredprocedurehere" 'Define name of Stored Procedure to execute.

    cmd.CommandType = adCmdStoredProc 'Define the ADODB command
    cmd.ActiveConnection = oConn 'Set the command connection string
    cmd.CommandText = stProcName 'Define Stored Procedure to run

    Set prmUser = cmd.CreateParameter("@user", adVarChar, adParamInput, 7)
    prmUser.Value = strUser
    cmd.Parameters.Append prmUser

    Set prmApplication = cmd.CreateParameter("@application", adInteger, adParamInput)
    prmApplication.Value = 1
    cmd.Parameters.Append prmApplication

    Set rs = cmd.Execute

    Range("A1").CopyFromRecordset rs '' to copy data in recordset to excel.

'' or you can do like this

   Set rs = cmd.Execute
    Do Until rs.EOF
       '' Do Something
    rs.MoveNext
    Loop