存储过程执行后关闭记录集



我正在VBA中使用ADO执行存储过程。我正在尝试使用SQLServer2008中存储过程的结果填充记录集。下面的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...上接收到错误Operation is not allowed when the object is closed,这向我指示存储过程没有返回结果。

但是,如果我在SSMS中执行存储过程,它将返回一行。SP遵循以下路线:

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

有人能帮忙解释为什么记录集被关闭/没有被填充吗?

基于类似的问题:在执行我在注释中建议的存储过程时,"对象关闭时不允许操作":

我怀疑有两个原因:1)您的sp不包含:SET NOCOUNT ON;;2)您正在处理类型为table的变量。

Operation is not allowed when the object is closed最常见的原因是该存储过程不包含SET NOCOUNT ON命令,这可以防止额外的结果集干扰SELECT语句。

有关详细信息,请参阅:SET NOCOUNT(Transact-SQL)