sql实现分页

时间:2021-08-14 20:05:15
  IF EXISTS(SELECT * FROM sysobjects WHERE name='usp_getPage')
DROP PROC usp_getPage
GO
CREATE PROC usp_getPage
@totalCount INT OUTPUT,
@PageIndex int=1,
@PageCount INT=5
AS
SELECT * FROM (SELECT ROW_NUMBER() OVER(ORDER BY classid) AS id,* FROM dbo.Class) AS temp WHERE id BETWEEN
@PageCount*(@PageIndex-1)+1 AND @PageCount*@PageIndex
SET @totalCount=CEILING((SELECT COUNT(*) FROM dbo.Class)*1.0/@PageCount)
GO DECLARE @count INT
exec usp_getPage @count OUTPUT,2,2
PRINT @count

主要是 ROW_NUMBER() OVER()函数可以从1开始给select到的数据集标号

然后,ceiling()函数可以获取与相应值相近的最大整数,如:ceiling(2.1)=3