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

前端之家收集整理的这篇文章主要介绍了sql – 如何从存储过程中检索标量值(ADO.NET)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果在存储过程中,我只执行一个语句,从soMetable选择count(*),然后从客户端(我使用C#ADO.Net sqlCommand调用存储过程),我怎样才能检索count(*)值?我正在使用sql Server 2008.

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

提前致谢,
乔治

解决方法

您可以使用Execute Scalar作为Andrew建议 – 或者您必须稍微更改一下代码
  1. CREATE PROCEDURE dbo.CountRowsInTable(@RowCount INT OUTPUT)
  2. AS BEGIN
  3. SELECT
  4. @RowCount = COUNT(*)
  5. FROM
  6. SoMetable
  7. END

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

  1. using(sqlCommand cmdGetCount = new sqlCommand("dbo.CountRowsInTable",sqlConnection))
  2. {
  3. cmdGetCount.CommandType = CommandType.StoredProcedure;
  4.  
  5. cmdGetCount.Parameters.Add("@RowCount",sqlDbType.Int).Direction = ParameterDirection.Output;
  6.  
  7. sqlConnection.Open();
  8.  
  9. cmdGetCount.ExecuteNonQuery();
  10.  
  11. int rowCount = Convert.ToInt32(cmdGetCount.Parameters["@RowCount"].Value);
  12.  
  13. sqlConnection.Close();
  14. }

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

猜你在找的MsSQL相关文章