技术交流群:171880541
------------------------------------------------------------------------------------------------------------------------------------
Create Procedure usp_Paging1
@tableName nvarchar(50),--要分页的表,如果是多表查询,请使用 Student,Score,Class的形式。@primaryKey nvarchar(20),--表的主键,该主键字段用于Row_Number函数的 over(order by)中@orderCondition nvarchar(100),--排序条件,如 id desc,name asc@pageIndex int=1,--当前要先是的第几页,默认显示第一页@pageSize int=10,--每页大小,默认每页显示10条@pageCondition nvarchar(100),--用于where部分的条件,先帅选出数据在分页,如果是多表查询,这里就必须包含类似于Student.id=score.id的形式@rowCount int output,--记录总共有多少条记录@pageCount int outputasbegin declare @sql nvarchar(max),@sqlPaging nvarchar(max),@total int--@total用来记录某个条件下的记录总数 set @sql=N'select @count=count(*) from '+@tableName set @sqlPaging=N'select * from (select Row_Number() over(order by '+@primaryKey+') RowIndex,* from '+@tableName+') As tmp ' --如果分页是有条件的 if(@pageCondition is not NULL and len(RTRIM(LTRIM(@pageCondition)))>0) begin set @sql=@sql+N' where '+@pageCondition--求出指定条件下的有多少条记录 set @sqlPaging=N'select * from (select Row_Number() over(order by '+@primaryKey+') RowIndex,* from '+@tableName+' where '+@pageCondition+') As tmp ' end --获得总共有多少条记录 exec sp_executesql @stmt=@sql,@params=N'@count int output',@count=@total output set @rowCount=@total set @pageCount=ceiling((@total*1.0/@pageSize))--求出总共有多少页 set @sqlPaging=@sqlPaging+N'where tmp.RowIndex between '+Convert(varchar(50),((@pageIndex-1)*@pageSize+1))+' and '+cast((@pageIndex*@pageSize) as varchar(50)) if(@orderCondition is not null and len(RTRIM(LTRIM(@orderCondition)))>0) begin set @sqlPaging=@sqlPaging+' order by '+ @orderCondition end exec sp_executesql @stmt=@sqlPagingendgodeclare @sum int,@rowCount intexec usp_Paging1 @tableName='Student',@primaryKey='id',@orderCondition='id desc',@pageIndex=1,@pageSize=20,@pageCondition='id>10', @pageCount=@sum output,@rowCount=@rowCount outputselect @sum as 总页数,@rowCount 总记录条数 ---------------------------------------------------------------------------------------------------------本人声明,以上仅代表个人理解,且于个人水平有限, 如有错误,不妥的地方,希望多多包涵,更希望路过高手能指正,以免误导读者。 337901356