如何从存储过程中检索标量值(ADO.NET)

Geo*_*ge2 7 sql ado.net stored-procedures sql-server-2008

如果在存储过程中,我只执行一个语句,select count(*) from sometable然后从客户端(我使用C#ADO.Net SqlCommand来调用存储过程),我该如何检索该count(*)值?我正在使用SQL Server 2008.

我很困惑,因为count(*)它不用作存储过程的返回值参数.

乔治,提前谢谢

mar*_*c_s 7

您可以使用ExecuteScalar作为Andrew建议 - 或者您必须稍微更改一下代码:

CREATE PROCEDURE dbo.CountRowsInTable(@RowCount INT OUTPUT)
AS BEGIN
  SELECT
    @RowCount = COUNT(*)
  FROM 
    SomeTable
END
Run Code Online (Sandbox Code Playgroud)

然后使用此ADO.NET调用来检索值:

using(SqlCommand cmdGetCount = new SqlCommand("dbo.CountRowsInTable", sqlConnection))
{
  cmdGetCount.CommandType = CommandType.StoredProcedure;

  cmdGetCount.Parameters.Add("@RowCount", SqlDbType.Int).Direction = ParameterDirection.Output;

  sqlConnection.Open();

  cmdGetCount.ExecuteNonQuery();

  int rowCount = Convert.ToInt32(cmdGetCount.Parameters["@RowCount"].Value);

  sqlConnection.Close();
}
Run Code Online (Sandbox Code Playgroud)

PS:但是在这个具体的例子中,我认为只是执行的替代方案ExecuteScalar更简单,更容易理解.如果您需要返回多个值(例如,来自多个表等的计数),则此方法可能正常工作.


And*_*are 6

当您执行查询调用时ExecuteScalar- 这将返回结果.

执行查询,并返回查询返回的结果集中第一行的第一列.其他列或行将被忽略.

由于您只返回一个值,因此只返回count表达式中的值.您需要将此方法的结果转换为int.