SQLServer常用分頁方式


  mysql的分頁是基於limit關鍵字,oracle的分頁是基於rownum行號,SQLserver的分頁在下面進行研究,是基於SQLServer2012進行的測試。

0.原來的SQL的所有數據

 

下面的測試假設每頁都是取5條數據。

1.第一種-ROW_NUMBER() OVER()方式(over函數必須有)

 (1)取第一頁數據

  select * from ( 
    select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user] 
  ) as b

      where RowId between 1 and 5;

 結果:

 

(2)取第二頁數據

  select * from ( 
    select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user] 
  ) as b

      where RowId between 6 and 10;

結果:

 

 總結:  這種方式采用    RowId BETWEEN 當前頁數-1*頁大小+1  and 頁數*頁大小   ,而且包含起始值與結束值。

 

補充:這種方式的通用寫法如下:   原來SQL不能帶order by ,但是可以帶條件。

原來SQL =     select * from [mydb].[dbo].[user] where name like 'name%'    

拼接分頁的模板如下: 

 select * from ( 
    select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from    (
            原來SQL
        ) AS A
) as B
where RowId between 1 and 5;

 

 

 

2.第二種-offset start fetch next page rows only

(1)取第一頁

select * from [mydb].[dbo].[user]   order by ID offset 0 rows fetch next 5 rows only;

結果:

 

 

(2)取第二頁

select * from [mydb].[dbo].[user]   order by ID offset 5 rows fetch next 5 rows only;

結果:

 

 總結:這種方式的起始值與結束值計算方式: offset 頁號*頁大小 rows fetch next 頁大小 rows only  

 

3.第三種: top 關鍵字

 (1)取第一頁

select top 5 * from [mydb].[dbo].[user] 
where ID not in (select top 0 ID from [mydb].[dbo].[user]);

結果:

 

(2)取第二頁

select top 5 * from [mydb].[dbo].[user] 
where ID not in (select top 5 ID from [mydb].[dbo].[user]);

結果:

 

  總結:這種方式只用改內層的 top就可以了:  內層的top后面相當於起始值,計算方式為  (頁號-1)*頁大小。

  補充:這種分頁方式的通用模板如下:  這個可以加order by和條件

原來SQL = select * from [mydb].[dbo].[user] where name like 'name%'   

select top 5 * from ( 
    原來SQL
) AS A where ID not in (select top 5 ID from [mydb].[dbo].[user]);

 

 

4.  ROW_NUMBER() + top 相當於上面1和3的結合使用

 (1)取第一頁

select top (5) * from (select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user]) as A where A.RowId>0;

結果:

(2)取第二頁

select top (5) * from (select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from [mydb].[dbo].[user]) as A where A.RowId>5;

結果:

 

  總結:這種方式比較通用, 第一個 top 里面的值 相當於 頁大小,第二個rowID>起始值,起始值計算方式為  (頁號-1)*頁大小

補充:這種分頁方式的通用模板如下:    這種方式原來的SQL也不用加排序語句

原來SQL = select * from [mydb].[dbo].[user] where name like 'name%'   

select top (5) * from (
    select *, ROW_NUMBER() OVER(Order by ID ) AS RowId from (
        原來SQL
        ) as A   
) as B where B.RowId>5;

 

 

注意:文中SQLServer的AS A這些起別名不能省略。

 


免責聲明!

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



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