在VBA中派生存储过程的参数

在VBA中派生存储过程的参数,vba,excel,sqlcommandbuilder,Vba,Excel,Sqlcommandbuilder,我试着找了很多地方,但都找不到我要找的东西 我想用vba编写一个子例程,告诉我存储在SQL Server上的存储过程的参数 我知道如何使用excel vba中的参数执行存储过程。我已经编写了一个存储过程,它接受一个存储过程名称并返回参数。所以我可以用这个。但我想也许有更好的方法我不知道。我发现了一个用于VB的SQLCommandBuilder类,它非常完美,但我需要在VBA中使用它。这在VBA中可用吗?我不知道在哪里激活它 谢谢 **附加信息:在下面有用的评论之后,我离我的目标越来越近了。 我希

我试着找了很多地方,但都找不到我要找的东西

我想用vba编写一个子例程,告诉我存储在SQL Server上的存储过程的参数

我知道如何使用excel vba中的参数执行存储过程。我已经编写了一个存储过程,它接受一个存储过程名称并返回参数。所以我可以用这个。但我想也许有更好的方法我不知道。我发现了一个用于VB的SQLCommandBuilder类,它非常完美,但我需要在VBA中使用它。这在VBA中可用吗?我不知道在哪里激活它

谢谢

**附加信息:在下面有用的评论之后,我离我的目标越来越近了。 我希望能够将任何存储过程传递到我的子例程中,它将能够计算出它需要多少参数以及它们是什么

这是到目前为止我的代码

Private Sub execStoredProcedureWithParameters(strServer As String, 

strDatabase As String, strSchema As String, strUSPName As String)

'Declare variables
Dim cmd As ADODB.Command
Dim conn As ADODB.Connection
Dim prm As ADODB.Parameter
Dim rs As ADODB.Recordset

Dim intParamCount As Integer

'Open database connection
Set conn = New ADODB.Connection
conn.ConnectionString = "Provider=sqloledb;Data Source=" + strServer + ";Initial Catalog=" + strDatabase + ";Integrated Security=SSPI;"
conn.CommandTimeout = 0

'Here's where the connection is opened.
conn.Open

'This can be very handy to help debug!
'Debug.Print conn.ConnectionString

Set cmd = New ADODB.Command
With cmd
    .CommandText = strSchema + "." + strUSPName
    .CommandType = adCmdStoredProc
    .ActiveConnection = conn
    .Parameters.Refresh

    For intParamCount = 0 To .Parameters.Count - 1
        Debug.Print .Parameters(intParamCount).Name, .Parameters(intParamCount).Type, .Parameters(intParamCounti).Size, .Parameters(intParamCount).Attributes, .Parameters(intParamCount).NumericScale

'        Set prm = cmd.CreateParameter(.Parameters(i).Name, adVarChar, adParamInput, 255)
'        cmd.Parameters.Append prm
'        cmd.Parameters(.Parameters(i).Name).Value = "DBName"
    Next

End With

Set rs = New ADODB.Recordset

'Execute the Stored Procedure
Set rs = cmd.Execute
'Populate the sheet with the data from the recordset
Sheet1.Range("RecordSet").CopyFromRecordset rs

'Cleanup
rs.Close
Set rs = Nothing
conn.Close
Set conn = Nothing

End Sub
关于参数。是否有方法将DataTypeEnum从值转换为常量。因此,对于第一个参数,当前的类型是202,根据这个表,我将其设置为adVarWChar


您可以使用ADODB执行此操作,添加对Microsoft ActiveX数据对象的引用,然后您可以:

With New ADODB.Command
    Set .ActiveConnection = myAdoDbConnection
    .CommandText = "[dbo].[usp_XXX]"
    .CommandType = adCmdStoredProc
    .Parameters.Refresh

    For i = 0 To .Parameters.Count - 1
        Debug.Print .Parameters(i).Name, .Parameters(i).Type, .Parameters(i).Direction
    Next
End With

应该有必要这样做,因为它需要往返到服务器。

如果您可以查询,那么,例如,like。这就是我的存储过程所做的。我在问是否有办法不必运行查询来获取参数。而是使用vba来查找它们。类似于VB中的SQLCommandBuilder。也许这是最好的方法,但我想知道是否还有其他更好的方法?谢谢你的帮助