【发布时间】:2017-06-13 18:18:08
【问题描述】:
我在 Excel 中有一个 VBA 子程序。它需要调用 SQL Server 过程,并在消息框中显示调用结果。 (主要是因为我在维护别人的代码——否则,我不会使用 Excel。)
我创建了我的 SQL 语句来调用该过程。我有打开连接的潜艇。但是在显示该过程调用的结果的过程中,我仍然遗漏了一些东西。
这是我目前所拥有的:
Dim Today As Date
Dim result As Date
Dim sSQLStatement As String
Dim strDate As String
Dim Recordset As ADODB.Recordset
Today = DateTime.Now()
result = DateSerial(Year(Today), Month(Today) - 1, 1)
strDate = Year(result) & "-" & Format(Month(result), "00") & "-" & Format(Day(result), "00")
DBOpen
sSQLStatement = "set nocount on; EXEC [MySchema].[dbo].[MyProcedure] @END_DATE = N'" & strDate & "'"
MsgBox sSQLStatement
Dim i As Long
Dim Ary
Dim strMsg As String
Set Recordset = New ADODB.Recordset
With Recordset
.ActiveConnection = cnPubs 'this is defined elsewhere, used in the DBOpen call, and works
'I can call the execute and it works, but it fails here when I try to assign the results to the recordset
Recordset = cnPubs.Execute(sSQLStatement)
'I found this online and don't know yet if it works. I have to get past the statement above first.
If Not Recordset.EOF Then
Ary = Recordset.GetRows
For i = 0 To UBound(Ary, 2)
If i = 0 Then
strMsg = Ary(0, i)
Else
strMsg = strMsg & ", " & Ary(0, i)
End If
Next i
MsgBox strMsg, , UBound(Ary, 2) + 1 & " records"
End If
.Close
End With
DBClose
所以,如果我自己调用 cnPubs.Execute(sSQLStatement),我可以知道它正在运行。我打开和关闭连接就好了。但它应该返回一组多行,我需要显示它。我不想在任何地方将它们写入电子表格 - 它们应该只显示在消息框中。
【问题讨论】:
-
如果你在它调用GetRows之后就在行上放一个断点,有多少条记录?
-
它并没有那么远。虽然,如果我从上面的行中删除“Recordset =”......我会试一试。
-
在 recordset= 行设置一个断点并告诉我 sSQLStatement 变量的含义(您可以将其打印到调试窗口)
标签: sql-server vba excel stored-procedures