2014-10-07 113 views
2

就像標題中提到的,我只想從VBA調用SQL Server存儲過程。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) 

DateDate類型,NrString類型。

我會很高興,如果有人能解釋我,我怎麼能用兩個參數來處理它。

Regards

回答

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 
+0

這不起作用。我得到錯誤消息,典型不兼容。 – Kipcak08 2014-10-07 10:29:41

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 
相關問題