在具有多个输出的VBA中执行SQL Server存储过程

时间:2015-08-19 19:38:30

标签: sql-server excel vba excel-vba stored-procedures

我在SQL Server中有一个存储过程,我试图通过一些VBA代码从Excel执行。但是,存储过程有两个输出(见下文)。

我的记录集只是拉入第一个表(添加了0个错误消息......)而我想拉入第二个表。

图片在这里:http://i.stack.imgur.com/LxyLi.png

这是我的代码,从我在这里找到的其他来源编译:

Sub RefreshBarcodes()
Dim Database As String
Dim con As ADODB.Connection
Dim strconn As String
Dim SQLServer As String
Dim Session As String
Dim strSQLCommandOne As String


Application.ScreenUpdating = False
Worksheets("Master").Activate
Database = Worksheets("Master").Cells(5, "H").Value
SQLServer = Worksheets("Master").Cells(4, "H").Value
Session = Worksheets("Master").Cells(6, "H").Value

'Connect to Database
Set con = New ADODB.Connection
strconn = "Provider=sqloledb; Data Source=" & SQLServer & ";Initial Catalog = " & _
Database & "; INTEGRATED SECURITY=SSPI; "
con.Open strconn

'Set SQL Commands
strSQLCommandOne = "set nocount on; exec spGetSessionSourceCounts 'HNW-CLU-001-024_01_0005'"

'Open Recordset
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset

'Execute and copy to Excel
rs.Open strSQLCommandOne, strconn
    rs.MoveFirst
    Worksheets("Session").Activate
    Cells(1, 1).Select
    ActiveCell.CopyFromRecordset rs
rs.Close

Worksheets("Master").Activate
Cells(6, "H").Value = "Session updated"

con.Close

Application.ScreenUpdating = True

End Sub

Excel输出:http://i.stack.imgur.com/b7i3B.png

我希望能够提取第一个(错误消息)和第二个结果(会话信息),但主要只需要第二个表。非常感谢提前!

1 个答案:

答案 0 :(得分:0)

要访问第二个记录集,您需要执行以下行: -

'Activate the next available recordset
Set rs = rs.NextRecordset

If Not rs Is Nothing Then

  'Add code in here

End If