【问题标题】:Recordset Closed After Stored Procedure Execution存储过程执行后记录集关闭
【发布时间】:2015-04-24 23:34:04
【问题描述】:

我正在使用 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... 行收到错误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

谁能帮助解释为什么记录集被关闭/未填充?

【问题讨论】:

  • 要确定有多少条记录受到了 SP 的影响,请使用 Exceute 方法和参数:msdn.microsoft.com/en-us/library/windows/desktop/… 而不是 BOF 和 EOF
  • @MaciejLos 感谢您的回复。由于正在执行多个 SP,因此影响了多行。您是否建议在尝试使用记录集之前检查这一点?谢谢
  • 是的。在这种情况下,不需要检查 BOF 和 EOF 方法返回的值。如果 RecordsAffected 参数返回大于零的值,则记录集将填充值 ;)
  • @MaciejLos 大多数情况下,受影响的记录将在 MS Access 中返回 -1。
  • 关注SET NOCOUNT ON 谢谢。将其粘贴在答案中,我会接受。再次感谢

标签: sql-server vba stored-procedures ado recordset


【解决方案1】:

基于类似问题:“Operation is not allowed when the object is closed” when executing stored procedure 我在评论中推荐:

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

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

更多信息请见:SET NOCOUNT (Transact-SQL)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多