如何使用 Excel VBA 字符串中的参数运行存储过程?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31986552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:53:59  来源:igfitidea点击:

How do I run a Stored procedure with parameters from Excel VBA string?

vbaexcel-vbastored-proceduresexcel

提问by ibexy

I am trying to run a stored procedure from Excel using VBA, but I'm getting a "Type Mismatch" error with the following code. Can I execute a Stored procedure with parameters as a string passed to the Command object as shown below?

我正在尝试使用 VBA 从 Excel 运行存储过程,但出现以下代码时出现“类型不匹配”错误。我可以使用参数作为传递给 Command 对象的字符串来执行存储过程,如下所示?

Function Sproc()
    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim cmd As ADODB.Command
    Dim ConnectionString As String
    Dim StrSproc As String

    ConnectionString = "Provider=SQLOLEDB;Data Source=DBSource;" & _
                  "Initial Catalog=CurrentDb;" & _
                  "Integrated Security=SSPI;"

    'Opens connection to the database
    cnn.Open ConnectionString

    'Timeout error in seconds for executing the entire query; this will run for 15 minutes
    'before VBA times out, but your database might timeout before this value

    cnn.CommandTimeout = 900

    StrSproc = "EXEC StoredProcedure " & _
                    "@parameter1 = 0," & _
                    "@parameter2 = 0," & _
                    "@parameter3 = 0,"

        Application.StatusBar = "Running stored procedure..."
        Set rst = cmd.Execute(, , StrSproc)
End Function

回答by paul bica

Try this:

尝试这个:

Option Explicit

Function Sproc()
    Dim cnn As New ADODB.Connection
    Dim rst As New ADODB.Recordset
    Dim cmd As ADODB.Command
    Dim cnnStr As String
    Dim Rs As New ADODB.Recordset
    Dim StrSproc As String

    cnnStr = "Provider=SQLOLEDB;Data Source=DBSource;" & "Initial Catalog=CurrentDb;" & _
             "Integrated Security=SSPI;"
    With cnn
        .CommandTimeout = 900
        .ConnectionString = cnnStr
        .Open
    End With
    With cmd
        .ActiveConnection = cnn
        .CommandType = adCmdStoredProc
        .CommandText = "[StoredProcedureName]"
        .Parameters.Append .CreateParameter("@parameter1", adInteger, adParamInput, , 0)
        .Parameters.Append .CreateParameter("@parameter2", adInteger, adParamInput, , 0)
        .Parameters.Append .CreateParameter("@parameter2", adInteger, adParamInput, , 0)
    End With
    With Rs
        .CursorType = adOpenStatic
        .CursorLocation = adUseClient
        .LockType = adLockOptimistic
        .Open cmd
    End With
    Application.StatusBar = "Running stored procedure..."
    Set rst = cmd.Execute
End Function

回答by Ralph

This is my preferred approach:

这是我的首选方法:

Function Sproc()
    Dim cnn As ADODB.Connection
    Dim rst As ADODB.Recordset
    Dim cmd As ADODB.Command
    Dim ConnectionString As String
    Dim StrSproc As String

    Set cnn = New ADODB.Connection
    cnn.ConnectionString = "Provider=SQLOLEDB;Data Source=DBSource;" & _
                  "Initial Catalog=CurrentDb;" & _
                  "Integrated Security=SSPI;"

    'Opens connection to the database
    On Error GoTo SQL_ConnectionError
    cnn.Open ConnectionString
    On Error GoTo 0
    'Timeout error in seconds for executing the entire query; this will run for 15 minutes before VBA timesout, but your database might timeout before this value
    cnn.CommandTimeout = 900

    Set rst = New ADODB.Connection
    StrSproc = "set nocount on; "
    StrSproc = StrSproc & "EXEC StoredProcedure " & _
                        "@parameter1 = 0," & _
                        "@parameter2 = 0," & _
                        "@parameter3 = 0 "
    rst.ActiveConnection = cnn
    On Error GoTo SQL_StatementError
    rst.Open StrSproc
    On Error GoTo 0

    If Not rst.EOF And Not rst.BOF Then
        Sproc = IIF(IsNull(rst.Fields(0).Value), "(BLANK)", rst.Fields(0).Value)
    EndIf

    Exit Function

    SQL_ConnectionError:
    Msgbox "Error connecting to the server / database. Please check the connection string."
    Exit Function

    SQL_StatementError:
    Msgbox "Error with the SQL syntax. Please check StrSproc."
    Debug.Print StrSproc
    Exit Function

End Function

Give it a try and let me know what you think.

试一试,让我知道你的想法。