简体   繁体   中英

Running stored procedure from Excel

I am trying to run a stored procedure from Excel. I know how to do it without using dynamic dates but I need the date range to be dynamic.

Sub TestStoredProcedure()

    Dim CServer As String
    Dim CDatabase As String
    Dim CLogon As String
    Dim CPass As String
    Dim StartDate As Date
    Dim EndDate As Date
    Dim TStartDate As String
    Dim TEndDate As String

    CServer = "111111"         ' Your server name here
    CDatabase = "111111"    ' Your  database name here
    CLogon = "11111111"     ' your logon here
    CPass = "111111"             ' your  password here

    Dim Cmd1 As New ADODB.Command
    Dim rs As New ADODB.Recordset
    Dim intTemp As Integer

    Set Cmd1 = New ADODB.Command

    Cmd1.ActiveConnection = cn
    Cmd1.CommandText = "callstatisticsbyQ"
    Cmd1.CommandType = adCmdStoredProc

    Cmd1.Parameters.Refresh
    Cmd1.Parameters(0).Value = Worksheets("Sheet2").Range("A1")
    Cmd1.Parameters(1).Value = Worksheets("Sheet2").Range("A2")
    Cmd1.Parameters(2).Value = Worksheets("Sheet2").Range("A3")

    Set rs = Cmd1.Execute()

    rs.Open Cmd1
    Worksheets("Procedure Export").Range("A1").CopyFromRecordset rs

    Call DumpSP("prcGetData", "", "", Worksheets("Procedure Export").Range("A1"))

End Sub

I get an error saying something about user defined type not defined .

To use ADO you click Tools->references in the VBA IDE & tick "Microsoft ActiveX Data Objects" - preferably the highest version thereof.

Additionally you use cn as the connection but its not defined in that sub (assuming its not global) & you will may need to Set Cmd1.ActiveConnection = cn .

Also take a look at this , it defines the input ( adParaminput ) paramaters in advance rather than using .Refresh which is pretty inefficient (takes a trip to the server)

Update for example :

rem for create procedure callstatisticsbyQ (@i int, @c varchar(10)) as select 1234;

Dim cn As ADODB.Connection
Dim Cmd1 As ADODB.Command
Dim rs As ADODB.Recordset

Set cn = New ADODB.Connection
Set Cmd1 = New ADODB.Command
Set Cmd1 = New ADODB.Command

cn.Open "Provider=SQLNCLI10;Server=1.2.3.4;Database=x;Uid=x; Pwd=x;"

Set Cmd1.ActiveConnection = cn
Cmd1.CommandText = "callstatisticsbyQ"
Cmd1.CommandType = adCmdStoredProc
Cmd1.Parameters.Append Cmd1.CreateParameter("p1", adInteger, adParamInput, , Worksheets("Sheet2").Range("A1"))
Cmd1.Parameters.Append Cmd1.CreateParameter("p2", adVarChar, adParamInput, 20, Worksheets("Sheet2").Range("A2"))

Set rs = Cmd1.Execute()
MsgBox rs(0)

rs.Close
cn.Close

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM