SQLServer分頁


一、創建測試表

CREATE TABLE [dbo].[Student](
    [id] [int] NOT NULL,
    [name] [nvarchar](50) NULL,
    [age] [int] NULL)

二、創建測試數據

declare @i int
set @i=1
while(@i<10000)
begin
    insert into Student select @i,left(newid(),7),@i+12
    set @i += 1
end

三、測試

1、使用top關鍵字

top關鍵字表示跳過多少條取多少條

declare @pageCount int  --每頁條數
declare @pageNo int  --頁碼
declare @startIndex int --跳過的條數
set @pageCount=10
set @pageNo=3
set @startIndex=(@pageCount*(@pageNo-1)) 
select top(@pageCount) * from Student
where ID not in
(
  select top (@startIndex) ID from Student order by id 
) order by ID

 測試結果:

2、使用row_number()函數

declare @pageCount int  --頁數
declare @pageNo int  --頁碼
set @pageCount=10
set @pageNo=3
--寫法1:使用between and 
select t.row,* from 
(
   select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row between (@pageNo-1)*@pageCount+1 and @pageCount*@pageNo
--寫法2:使用 “>”運算符
 select top (@pageCount) * from 
(
   select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row >(@pageNo-1)*@pageCount
--寫法3:使用and運算符 
select top (@pageCount) * from 
(
   select ROW_NUMBER() over(order by ID asc) as row,* from Student
) t where t.row >(@pageNo-1)*@pageCount and t.row<(@pageNo)*@pageCount+1

四、總結

ROW_NUMBER()只支持sql2005及以上版本,top有更好的可移植性,能同時適用於sql2000及以上版本、access。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM