作為程式設計師來說,與資料庫打交道是十分頻繁的分頁查詢是一個開發者必須掌握的基本知識點,目前整理了下面三種SQLServer分頁查詢語句的寫法,僅供參考。
一、Top Not IN 方式(查詢靠前的資料較快)語法格式:
select top 條數 * from tablename where Id not in (select top pageSize*(pageIndex-1) Id from tablename)
示例:
SELECT TOP 2 * FROM Users WHERE Id NOT IN (SELECT TOP 2 Id FROM Users)
二、ROW_NUMBER() OVER()方式 (查詢靠後的資料速度較快)
語法格式:
SELECT * FROM (SELECT *, ROW_NUMBER() OVER(Order by Id ) AS RowNumber from tablename ) as b where RowNumber between pageIndex-1*pageSize and pageIndex*pageSize
示例:
SELECT * FROM ( SELECT *, ROW_NUMBER() OVER (ORDER BY Id) AS RowNumber FROM Users ) as b where RowNumber BETWEEN 0 and 5
三、offset fetch next方式 (速度更優,限制Sql2012版本以上可以使用)語法格式:
select * from tablename order by Id offset pageIndex row fetch next pageSize row only
示例:
select * from Users order by Id offset 2 row fetch next 5 row only
四、分頁儲存過程
create PROCEDURE GetPageData(@TableName varchar(30),--表名稱@IDName varchar(20),--表主鍵名稱@PageIndex int,--當前頁數@PageSize int--每頁大小)ASIF @PageIndex > 0BEGINset nocount onDECLARE @PageLowerBound int,@StartID int,@sql nvarchar(225)SET @PageLowerBound = @PageSize * (@PageIndex-1)IF @PageLowerBound<1SET @PageLowerBound=1SET ROWCOUNT @PageLowerBoundSET @sql=N'SELECT @StartID = ['+@IDName+'] FROM '+@TableName+' ORDER BY '+@IDNameexec sp_executesql @sql,N'@StartID int output',@StartID outputSET ROWCOUNT 0SET @sql='select top '+str(@PageSize) +' * from '+@TableName+' where ['+@IDName+']>='+ str(@StartID) +' ORDER BY ['+@IDName+'] 'EXEC(@sql)set nocount offEND