SQL Server 2012使用Offset/Fetch Next實現分頁

來源:互聯網
上載者:User

標籤:etc   fse   order   pre   結果   bsp   資料庫   name   order by   

在Sql Server 2012之前,實現分頁主要是使用ROW_NUMBER(),在SQL Server2012,可以使用Offset ...Rows  Fetch Next ... Rows only的方式去實現分頁資料查詢。

select [column1]      ,[column2]      ...          ,[columnN]from [tableName]order by [columnM]offset (pageIndex-1)*pageSize rowsfetch next pageSize rows only

 

上面代碼中,column1,column2 ... columnN表示實現需要查詢的列,tableName是表名,columnM是需要排序的列名,pageIndex是頁碼,pageSize是每頁資料的大小,實際中一般是先計算(pageIndex-1)*pageSize的結果,然後在sql裡直接使用具體的結果(數字)

例如資料庫中有T_Student表,資料如下:

 

 假如需要查詢第3頁的資料(由於資料少,這裡假設每頁資料是2條,即pageSize=2),那麼SQL語句如下:

select [Id]      ,[Name]      ,[StudentId]      ,[MajorId]from T_Studentorder by [Id]offset 4 rowsfetch next 2 rows only

結果如下:

 

注意:使用Offset /Fetch Next需要指定排序,即必須有order by ***

SQL Server 2012使用Offset/Fetch Next實現分頁

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.