1

我已经尝试搜索了很多地方,但找不到我要找的东西。

我想在 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 从值转换为常量。因此,根据此表,我将设置为 adVarWChar 的第一个参数的类型当前为 202

https://docs.microsoft.com/en-us/sql/ado/reference/ado-api/datatypeenum

4

1 回答 1

1

您可以使用 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

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

于 2017-04-27T15:45:17.253 回答