使用两个参数从

时间:2016-02-09 13:39:38

标签: excel vba excel-vba

我现在有3天的困难,现在尝试使用带有两个参数的存储过程从sql Server检索数据。我一直在收到ERROR 3704.这是记录集的全部内容,我并没有真正进一步了解。

有趣的是,这个`vba代码在没有参数的情况下工作。

Public Sub getRecords()

Dim con As ADODB.Connection
Dim cmd As ADODB.Command
Dim rs As ADODB.Recordset
Dim par As String
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 where we want to put our Stored Procedure's results.

    Dim rngRange As Range
    Set rngRange = Range(Cells(20, 1), Cells(Rows.Count, 1)).EntireRow
    rngRange.ClearContents

    ' Log into our SQL Server, and run the Stored Procedure
    con.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=myServer;Initial Catalog=myDataBase"
    cmd.ActiveConnection = con
    cmd.CommandType = adCmdStoredProc

    cmd.CommandTimeout = 0

    'Set up the parameter for our Stored Procedure
    cmd.Parameters.Append cmd.CreateParameter("Periode1", adVarChar, adParamInput, 10, Range("E9").Text)
    cmd.Parameters.Append cmd.CreateParameter("Periode2", adVarChar, adParamInput, 10, Range("E11").Text)

    Application.StatusBar = "Running stored procedure..."
    cmd.CommandText = "spTest"
    Set rs = cmd.Execute(, , adCmdStoredProc)

    'Copy the results to cell B7 on the first Worksheet
    Set WSP1 = Tabelle2
    WSP1.Activate
    'If rs.EOF = False Then Range(Cells(2, 1), Cells(Rows.Count, 1)).EntireRow

    If rs.EOF = False Then WSP1.Cells(2, 1).CopyFromRecordset rs

    rs.Close
    Set rs = Nothing
    Set cmd = Nothing

    con.Close
    Set con = Nothing

    Application.StatusBar = "Data successfully updated."

End Sub

运行时错误在此行:

If rs.EOF = False Then

会感谢帮助或替代

1 个答案:

答案 0 :(得分:0)

存储过程应该返回表:

CREATE PROCEDURE spTest

@Param1 AS INT,
@Param2 as INT
AS

BEGIN

  SELECT TOP 10 * FROM Test
  WHERE Param1=@Param1
  AND   Param2=@Param2
END

如果不按程序返回表但值

,则会显示此错误