使用SQL Server内置的row_number() over (order by fieldName) 行号实现简单的数据分页查询。
参数说明:1、查询SQL语句,必须在尾部加上排序;2、当前页码;3、每页显示的条数;4、(输出参数)当前SQL语句查询到的数据总条数。
USE databasename
if Exists(select name from sysobjects where NAME = 'pro_Common_PageView' and type='P')
drop procedure pro_Common_PageView
GO
CREATE PROC pro_Common_PageView
@sql nvarchar(3000), --要执行的sql语句(注:必须加上排序)
@PageCurrent int=1, --要显示的页码
@PageSize int=10, --每页的大小
@AllRows int OUTPUT --总条数
AS
declare @countSql nvarchar(3000);--总条数SQL
declare @orderByIndex int;--原ORDERBY的索引
declare @orderBySql nvarchar(3000);--order by SQL
declare @PageCount int;--总页数
SET NOCOUNT ON
select @orderByIndex=charindex('order by',@sql,16);
if @orderByIndex>16
begin
select @orderBySql=substring(@sql,@orderByIndex,len(@sql));
select @sql=substring(@sql,charindex('select',@sql,1)+6,@orderByIndex-8);
end
else
select @sql=substring(@sql,charindex('select',@sql,1)+6,len(@sql));
--基础SQL
set @sql='select * from (select row_number() over ('+@orderBySql+') as row_number_ids,'+@sql+') row_all_table';
--统计总条数
set @countSql='select @tatolCount=max(row_number_ids) from ('+@sql+') tab_stat_tatol_count';
exec sp_executesql @countSql,N'@tatolCount int output',@AllRows output ;
--计算总页数
IF ISNULL(@PageSize,0)<1
SET @PageSize=10;
SET @PageCount=(@AllRows+@PageSize-1)/@PageSize;
IF ISNULL(@PageCurrent,0)<1
SET @PageCurrent=1;
ELSE IF ISNULL(@PageCurrent,0)>@PageCount
SET @PageCurrent=@PageCount;
--分页SQL
set @sql=@sql+' where row_number_ids >'+str(((@PageCurrent-1)*@PageSize))+' and row_number_ids <='+str((@PageCurrent*@PageSize));
exec(@sql);
GO