Optimal ms SQL server paging SQL statements

Source: Internet
Author: User

 

Author: yanek
Email: yanek@126.com

Feature: only one page of data is returned for a single query. Instead of getting all the data.
Note:

Pagesize: number of records displayed per page
Cureentpage: Current page number

Select * from (select TOP pagesize * FROM (select top pagesize * cureentpage * from user_table order by id ASC) as aSysTable order by id DESC) as bSysTable order by id ASC

Example:

Assume that the database table is as follows:

User_table:

Id: primary key, auto-Increment
Username: character
Password: character

Assume there are 80 records, and 10 records are displayed on each page, with IDs ranging from 1 to 80.

Now the data on the third page is sorted in ascending order by id: The obtained Record id should be 21 to 30.

The statement should be:

Select * from (select TOP 10 * FROM (select top 30 * from user_table order by id ASC) as aSysTable order by id DESC) as bSysTable order by id ASC

The principle is as follows:

First, 30 records (3*10) are retrieved in ascending ORDER of IDS, that is, records with IDs between 1 and 30 (select top 30 * from user_table order by id ASC)

Then sort the 30 records in descending order by ID.

Then, extract the first 10 records from the 30 records: The obtained records are: IDs are between 30 and 21. This is the data we need, but it is arranged in descending order and does not meet the requirements.

Finally, the data we need will be obtained after re-sorting. The id is between and 30.

Hope to help you.

If you have any questions, I hope to share them with you.

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.