我在使用VBA中的ADO执行存储过程。 我试图将来自SQL Server 2008存储过程的结果填充到记录集中。以下是VBA示例:
Public Function DoSomething() As Variant()
Dim oDB As ADODB.Connection: Set oDB = New ADODB.Connection
Dim oCM As ADODB.Command: Set oCM = New ADODB.Command
Dim oRS As ADODB.Recordset
oDB.Open gcConn
With oCM
.ActiveConnection = oDB
.CommandType = adCmdStoredProc
.CommandText = "spTestSomething"
.NamedParameters = True
.Parameters.Append .CreateParameter("@Param1", adInteger, adParamInput, , 1)
Set oRS = .Execute
End With
If Not oRS.BOF And Not oRS.EOF Then 'Error thrown here'
DoSomething = oRS.GetRows()
Else
Erase DoSomething
End If
oRS.Close
Set oRS = Nothing
oDB.Close
Set oDB = Nothing
End Function
我收到了错误信息
对象关闭时不允许操作
,该错误出现在代码行If Not oRS.BOF...
。这告诉我存储过程没有返回结果。然而,如果我在SSMS中执行存储过程,它会返回一行结果。该存储过程大致如下:
CREATE PROC spTestSomething
@Param1 int
AS
BEGIN
DECLARE @TempStore table(id int, col1 int);
INSERT INTO table1
(param1)
OUTPUT inserted.id, inserted.col1
INTO @TempStore
VALUES
(@Param1);
EXEC spOtherSP;
SELECT
id,
col1
FROM
@TempStore;
END
GO
在SSMS中执行该过程的结果如下:
id col1
__ ____
1 1
有人可以帮忙解释一下为什么记录集被关闭或未填充吗?
Execute
方法与参数一起使用:https://msdn.microsoft.com/en-us/library/windows/desktop/ms681559%28v=vs.85%29.aspx,而不是BOF和EOF。 - Maciej LosSET NOCOUNT ON
是完全正确的,谢谢。把它放在回答中,我会接受的。再次感谢。 - Gareth