Welcome

首页 / 软件开发 / .NET编程技术 / .NET分页存储过程代码及使用

.NET分页存储过程代码及使用2014-03-28 博客园 初行最近需要做个论坛,其中用到了分页,如果把整表的数据都查询出来未免小题大做,而且还影响速度 ,所以百度了并私有化了一个分页存储过程,实现了调用。

好了,废话不多说,贴出代码:

/****使用帮助首先查询表总行数,再查询分页数据查询行数传入参数:@doCount,@tblName查询分页传入参数:@tblName,@PageSize,@PageIndex,@fldName*以上不带查询条件的查询带条件的加参数:@strWhere*分页查询可以使用排序参数:@OrderType****/create PROCEDURE Sp_Conn_Sort(@tblName varchar(255), -- 表名@strGetFields varchar(1000) = "*",-- 需要返回的列 @fldName varchar(255)="",-- 排序的字段名@PageSize int = 40,-- 页尺寸@PageIndexint = 1, -- 页码@doCountbit = 0, -- 返回记录总数, 非 0 值则返回@OrderType bit = 0,-- 设置排序类型, 非 0 值则降序@strWherevarchar(1500)=""-- 查询条件 (注意: 不要加 where))ASdeclare @strSQL varchar(5000) -- 主语句declare @strTmp varchar(110)-- 临时变量declare @strOrder varchar(400)-- 排序类型 if @doCount != 0beginif @strWhere !=""set @strSQL = "select count(*) as Total from " + @tblName + " where "+@strWhereelseset @strSQL = "select count(*) as Total from " + @tblName end--以上代码的意思是如果@doCount传递过来的不是0,就执行总数统计。以下的所有代码都是@doCount为0的情况elsebegin if @OrderType != 0beginset @strTmp = "<(select min"set @strOrder = " order by " + @fldName +" desc"--如果@OrderType不是0,就执行降序,这句很重要!endelsebeginset @strTmp = ">(select max"set @strOrder = " order by " + @fldName +" asc"end if @PageIndex = 1beginif @strWhere != "" set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ "from " + @tblName + " where " + @strWhere + " " + @strOrder else set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ "from "+ @tblName + " "+ @strOrder--如果是第一页就执行以上代码,这样会加快执行速度endelsebegin--以下代码赋予了@strSQL以真正执行的SQL代码set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ "from "+ @tblName + " where " + @fldName + "" + @strTmp + "("+ @fldName + ") from (select top " + str((@PageIndex-1)*@PageSize) + " "+ @fldName + " from " + @tblName + "" + @strOrder + ") as tblTmp)"+ @strOrder if @strWhere != ""set @strSQL = "select top " + str(@PageSize) +" "+@strGetFields+ "from "+ @tblName + " where " + @fldName + "" + @strTmp + "("+ @fldName + ") from (select top " + str((@PageIndex-1)*@PageSize) + " "+ @fldName + " from " + @tblName + " where " + @strWhere + " "+ @strOrder + ") as tblTmp) and " + @strWhere + " " + @strOrderend end exec (@strSQL)