存储过程的返回值不正确



我在SQL Server 2016中有以下存储过程:

SET NOCOUNT ON;
SELECT * FROM MyTable;
RETURN  @@ROWCOUNT

当我在 SSMS 中运行此过程时,返回值为 43,因为它应该是。

我的应用程序中有以下代码片段:

com = New SqlCommand("MyQuery", conn)
com.CommandType = CommandType.StoredProcedure
prm = New SqlParameter
With prm
    .DbType = DbType.Int32
    .Direction = ParameterDirection.ReturnValue
End With
com.Parameters.Add(prm)
conn.Open()
Dim rdr As SqlDataReader = com.ExecuteReader
While rdr.Read
    Debug.WriteLine(rdr(0))
End While
Debug.Write(prm.Value Is Nothing)

While 循环中的 Debug 语句打印出第一列中的所有数据,因此我知道它们都在协同工作,但最终 Debug 语句的结果为 True。 为什么我没有得到我的返回值?

编辑:答案在我的应用程序代码中,而不是在 SQL 中。 保持 SQL 不变,我通过将 prm 循环中的第二行更改为:

RetVal = ParameterDirection.ReturnValue

现在,RetVal 包含返回值。 现在看来,这显然是有道理的。

尝试稍微修改存储过程:

DECLARE @RetVal int
SET NOCOUNT ON;
SELECT * FROM MyTable;
SET @RetVal = @@ROWCOUNT
RETURN  @RetVal

如果这不起作用,请尝试@RetVal使用

SELECT @RetVal = COUNT(*) FROM MyTable

请按如下方式更新查询。

SELECT * FROM MyTable;
SELECT  @@ROWCOUNT as Row_Count

更新SP后,获取数据集中的数据,在数据集的第二个表中,您将获得行计数的值。

最新更新