按指定条件统计记录的存储过程(C#)
系统开发中会遇到这样的场景:根据所给定条件计算一下数据库中的记录的条数,经多方查询资料编写了一个通用的用于计数的存储过程:
通常的统计语句
select count(*) from Employees where Country='USA'
查询条件:Country='USA'
返回计数值为:5
CREATE PROCEDURE [dbo].[EmployeesCountByWhere]
@where varchar(8000) = ' 1=1 ',
@recordCount int output
AS
SET NOCOUNT ON
declare @sqlCount nvarchar(4000)
set @sqlCount= 'SELECT @Count=count(-1) FROM [dbo].[Employees] WHERE ' + @where
--print @sqlCount
exec sp_executesql @sqlCount,N'@Count int output',@recordCount output
执行该存储过程
输入的执行条件为:Country='USA'
DECLARE @RC int
DECLARE @where varchar(8000)
DECLARE @recordCount int
SELECT @where = ' Country=''USA'''
EXEC @RC = [Northwind].[dbo].[EmployeesCountByWhere] @where, @recordCount OUTPUT
DECLARE @PrnLine nvarchar(4000)
PRINT '存储过程: Northwind.dbo.EmployeesCountByWhere'
SELECT @PrnLine = ' 返回代码 = ' + CONVERT(nvarchar, @RC)
PRINT @PrnLine
PRINT ' 输出参数: '
SELECT @PrnLine = ' @recordCount = ' + isnull( CONVERT(nvarchar, @recordCount), '<NULL>' )
PRINT @PrnLine
返回结果
存储过程: Northwind.dbo.EmployeesCountByWhere
返回代码 = 0
输出参数:
@recordCount = 5
C#中的使用方法
/// <summary>
/// 得到数据表Employees满足查询条件的记录数
/// </summary>
/// <param name="where">查询条件</param>
/// <param name="recordCount">记录数</param>
public void Select(string where, out int recordCount)
{
//存储过程名称
string sqlCommand = "EmployeesCountByWhere";
//初始化参数
SqlParameter[] param ={
new SqlParameter("@where",SqlDbType.VarChar,8000),
new SqlParameter("@recordCount",SqlDbType.Int)
};
param[0].Value = where;
param[1].Direction = ParameterDirection.Output;
SqlHelper.ExecuteNonQuery(Conn.SqlConn, CommandType.StoredProcedure, sqlCommand, param);
//返回记录数
recordCount = Convert.ToInt32(param[1].Value);
}
前台页面调用该函数的需构造的where
//初始化字符串
String where = "Country='{0}'";
//s赋值
where = string.Format(where,"USA");
执行Select(where)即可获得与上面一样的统计结果:5
该存储过程使用起来非常的灵活, 针对一个数据库表,只需要编写一个存储过程,通过前台生成where查询条件,灵活控制程序的走向,减少了代码书写量。