CREATE PROCEDURE [dbo].[P_名称]--创建存储过程
@PageSize INT, --每页显示的项数
@PageIndex INT,--当前页数
@RecordCount INT OUTPUT --输出总行数
AS
BEGIN
--获取总行数,用count(*)
set @Sqlselect='select @RowCount=count(*) from [表名]';--语句
exec sys.sp_executesql @Sqlselect,N'@RowCount INT output',@RecordCount output;--将总页数赋给@RecordCount output
--查询总页数(CEILING()向上舍入)
DECLARE @PageCount int --声明
set @PageCount=CEILING(CONVERT(float,@RecordCount/@PageSize))--获取页数
--判断当查询的页数小于1时则查询首页,大于最大值则为最后一页
if(@PageIndex<1)
begin
set @PageIndex=1;
end
if(@PageIndex>@PageCount)
begin
set @PageIndex=@PageCount;
end
--查询分页数据(CONVERT),防止序号出现断层
set @Sqlselect= 'select * from (
select ROW_NUMBER() over(order by [--根据表里哪一列排序的列名称]) as rowindex ,[查询的表的数据]) a where a.rowindex >'+convert(nvarchar(32),(@PageSize*(@PageIndex-1)))+' and a.rowindex<='+CONVERT(nvarchar(32),(@PageSize*@PageIndex))+''
exec sp_executesql @Sqlselect
END
GO