如果在存储过程中,我只执行一个语句,从soMetable选择count(*),然后从客户端(我使用C#ADO.Net sqlCommand调用存储过程),我怎样才能检索count(*)值?我正在使用sql Server 2008.
我很困惑,因为count(*)不用作存储过程的返回值参数.
提前致谢,
乔治
解决方法
您可以使用Execute
Scalar作为Andrew建议 – 或者您必须稍微更改一下代码:
- CREATE PROCEDURE dbo.CountRowsInTable(@RowCount INT OUTPUT)
- AS BEGIN
- SELECT
- @RowCount = COUNT(*)
- FROM
- SoMetable
- END
然后使用此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();
- }
渣
PS:但在这个具体的例子中,我想只需执行ExecuteScalar的替代方案就更简单,更容易理解.如果您需要返回多个值(例如,来自多个表等的计数),则此方法可能正常.