通过ADO检索存储过程输出参数

时间:2013-11-12 11:56:26

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

我现在已经超过48小时了。我试图使用ADO对象检索输出参数值。这是我的vba代码。

Function ExecuteCommand(cSp As String, aParameters As Variant) As Integer

Dim lnReturn As Integer
Dim loCommand As ADODB.Command
Dim prm As ADODB.Parameter
Dim rds As ADODB.Recordset

Set loCommand = New ADODB.Command

loCommand.CommandText = cSp
loCommand.CommandType = adCmdStoredProc
Set loCommand.ActiveConnection = goConnection
loCommand.NamedParameters = True

Dim iCount As Integer

For iCount = LBound(aParameters) To UBound(aParameters)
    If aParameters(iCount, 0) <> "" Then
        If aParameters(iCount, 1) = adNumeric Then
            Set prm = loCommand.CreateParameter(aParameters(iCount, 0), aParameters(iCount, 1), adParamInput)
            prm.Precision = 18
            prm.NumericScale = 0
            prm.Value = aParameters(iCount, 3)
        Else
            Set prm = loCommand.CreateParameter(aParameters(iCount, 0), aParameters(iCount, 1), adParamInput, , aParameters(iCount, 3))
        End If
        loCommand.Parameters.Append prm
    End If
Next

Set prm = loCommand.CreateParameter("@returnval", adInteger, adParamOutput, , lnReturn)
loCommand.Parameters.Append prm

Set rds = loCommand.Execute
' Check the value of lnReturn and it's zero here.
lnReturn = loCommand.Parameters("@returnval").Value


ExecuteCommand = lnReturn

End Function

我的存储过程如下......

USE [table_name]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[spname]
@para1 int,
@para2 int,
@para3 int,
@returnval int Output
AS
BEGIN

SET NOCOUNT ON;

SELECT * FROM type_table WHERE type1=@para1 and type2=@para2 and type3=@para3
SET @returnval = @@ROWCOUNT
RETURN @returnval
END

这些是我的发现

lnReturn = 0 always
rds.EOF = False
rds.RecordCount = -1

我的问题是我没有得到正确的受影响的行数,即1。我不确定代码有什么问题,有人可以帮忙吗?

3 个答案:

答案 0 :(得分:4)

这可能是因为,正如Technet所说, In the case of output parameters and return values, the values are not returned until the data of the Recordset object has been fetched completely or the Recordset has been closed.

如果您对SELECT语句返回的数据不感兴趣,请关闭RecordSet(rds.Close),或者在读取所有行之前循环它。

顺便说一句,如果你从不对select语句返回的数据感兴趣,只对行计数感兴趣,那么返回它会更有效率。因此,如果您可以修改SP,则可以将其更改为:

SELECT @returnval = COUNT(*) FROM type_table WHERE type1=@para1 and type2=@para2 and type3=@para3

答案 1 :(得分:0)

从您的程序中删除SET NOCOUNT ON;后试用

我认为这会对你有所帮助。如果在过程中设置SET NOCOUNT ON;,则不会返回受影响的行计数。

答案 2 :(得分:0)

如果您不希望将记录集作为存储过程调用的一部分,请使用cmd1-&gt; Execute(NULL,NULL,ADO :: adExecuteNoRecords);