create procedure proc_pagination ( @pageSize int, ----每页显示的记录个数 @pageIndex int, ----要显示那一页的记录 @tblName nvarchar(200), ----要显示的表 @fldName nvarchar(500) = ' * ' , ----要显示的字段列表 @fldSort nvarchar(200) = null, ----排序字段列表或条件 @PK nvarchar(150) , ----主表的主键 @pkSort nvarchar(4) = 'asc', ----主键的排序asc/desc,默认为asc @condition nvarchar(1000) = null, ----查询条件,不需where,如“and 1=1 and 2>1” @Counts int output, ----总记录数 @pagesCount int output ----总的页数 ) AS set nocount on --声明 declare @sqlTmp nvarchar(1000), ----临时存储SQL语句 @sqlOrder1 nvarchar(200), ----正常排序 @sqlOrder2 nvarchar(200), ----倒序 @pageCut int, ----正序倒序分段点 @lastPageCnt int ----最页一页的记录数 --统计记录总数 if (@condition is not null) set @condition = ' where 1=1 '+@condition+' ' else set @condition = ' ' set @sqlTmp = N'select @counts=count(*) from '+@tblName+@condition exec sp_executesql @sqlTmp,N'@counts float output',@counts output --组织条件 if (@pkSort is null) set @pkSort='' if (@fldSort is not null) set @sqlOrder1 = @fldSort+','+@PK+' '+@pkSort else set @sqlOrder1 = @PK+' '+@pkSort --------- set @sqlOrder2 = replace(@sqlOrder1,'asc','[a|s|c]') set @sqlOrder2 = replace(@sqlOrder2,'desc','asc') set @sqlOrder2 = replace(@sqlOrder2,'[a|s|c]','desc') -------- set @sqlOrder1 = ' order by '+@sqlOrder1 set @sqlOrder2 = ' order by '+@sqlOrder2 --统计总页数 set @pagesCount = ceiling(@counts*1.0/@pageSize) set @pageCut = @pagesCount/2 --组织数据 if (@pageIndex<1) set @pageIndex=1 if (@pageIndex>@pagesCount) set @pageIndex=@pagesCount --组织分页查询语句 if (@pageIndex=1) begin set @sqlTmp='select top '+cast(@pageSize as varchar(10))+' '+@fldName+' from '+@tblName+@condition+@sqlOrder1 end else if (@pageIndex<@pageCut) begin set @sqlTmp='select * from (select top '+cast(@pageSize as varchar(10))+' * from (select top '+cast(@pageSize*@pageIndex as varchar(10))+' '+@fldName+' from '+@tblName+@condition+@sqlOrder1+') as tb1'+@sqlOrder2+') as tb2'+@sqlOrder1 end else if (@pageIndex>=@pageCut and @pageIndex<@pagesCount) begin declare @topCount int ----倒序选取的记录数 set @topCount = (@pagesCount-@pageIndex)*@pageSize set @lastPageCnt = @counts%@pageSize if (@lastPageCnt>0) set @topCount=@topCount+@lastPageCnt set @sqlTmp='select top '+cast(@pageSize as varchar(10))+' * from (select top '+cast(@topCount as varchar(10))+' '+@fldName+' from '+@tblName+@condition+@sqlOrder2+') as tb1'+@sqlOrder1 end else if (@pageIndex=@pagesCount) begin set @lastPageCnt = @counts%@pageSize if (@lastPageCnt>0) set @pageSize=@lastPageCnt set @sqlTmp='select * from (select top '+cast(@pageSize as varchar(10))+' '+@fldName+' from '+@tblName+@condition+@sqlOrder2+') as tb1'+@sqlOrder1 end --执行 exec sp_executesql @sqlTmp GO