SQL Server 2012 uses offset/fetch next for paging

Source: Internet
Author: User

Before SQL Server 2012, the implementation of paging was primarily using row_number (), in SQL Server2012, you can use the offset ... Rows Fetch Next ... Rows only way to implement paging data query.

Select [Column1]      ,[Column2]      ...          ,[ColumnN] from [TableName]Order  by [COLUMNM]offset (PageIndex-1)*pageSize rowsFetch NextPageSize rows only

in the code above, Column1,column2 ... columnn represents the column that implements the query, TableName is the table name, COLUMNM is the column name that needs to be sorted, pageindex is the page number, and pagesize is The size of the data per page, in practice is generally calculated first (pageIndex-1) *pagesize results, and then directly in SQL to use the specific results (numbers)

For example, the database has a t_student table with the following data:

If you need to query the data on page 3rd (since there is less data, assuming that the data per page is 2, or pagesize=2), then the SQL statement is as follows:

Select [Id]      ,[Name]      ,[StudentID]      ,[Majorid] fromt_studentOrder  by [Id]Offset4rowsFetch Next 2Rows only

The results are as follows:

Note: Use Offset/fetch next needs to specify the sort, which must have an ORDER by * * *

SQL Server 2012 uses offset/fetch next for paging

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.