SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: 潇潇与偕 -- Create date: -- Description: 分页存储过程 -- ============================================= create PROCEDURE p_Common_DataPager_New @sqlstr nvarchar(max), --SQL statement @currentpage int, --page # @pagesize int, --size of page @rowcount int output, @pagecount int output AS BEGIN set nocount on declare @countSql nvarchar(max) declare @dataSql nvarchar(max) declare @dbwhitespaceIndex int=0 declare @orderbyStr nvarchar(max) --处理掉多余空格 set @dbwhitespaceIndex=CHARINDEX(' ',@sqlStr) while @dbwhitespaceIndex>0 begin set @sqlStr=REPLACE(@sqlStr,' ',' ') set @dbwhitespaceIndex=CHARINDEX(' ',@sqlStr) end print ('@orderbyStr:'+@orderbyStr) --组装无排序字段的查询sql if CHARINDEX('ORDER BY',@sqlStr)=0 begin --截取排序字段 set @orderbyStr='' set @dataSql='declare @tempTable table ( TemplTableSortId int ); select top '+CONVERT(nvarchar(10),@pagesize)+' dt.* from ( select ROW_NUMBER() over(order by t.TemplTableSortId) sortid,s.* from ('+@sqlstr+') s left join @tempTable t on 0=1) dt where dt.sortid> '+convert(nvarchar(10),(@currentpage-1)*@pagesize) end --组装有排序字段的sql else begin select @orderbyStr= SUBSTRING(@sqlStr,CHARINDEX('ORDER BY',@sqlStr),LEN(@sqlStr)) set @dataSql='select top '+CONVERT(nvarchar(10),@pagesize)+' dt.* from ( select ROW_NUMBER() over('+@orderbyStr+') sortid,'+ SUBSTRING(@sqlStr,CHARINDEX('SELECT',@sqlStr)+6,LEN(@sqlStr)-len(@orderbyStr)-6)+') dt where dt.sortid>'+convert(nvarchar(10),(@currentpage-1)*@pagesize) end --查询总行数 set @countSql='select @totalcount=count(*) from ('+ SUBSTRING(@sqlStr,0,LEN(@sqlStr)-len(@orderbyStr))+') t' exec sp_executesql @countSql, N'@totalcount int out',@rowcount out --计算总页数 set @pagecount=@rowcount/@pagesize if @rowcount%@pagesize>0 begin set @pagecount+=1 end exec(@dataSql) set nocount off END GO