T-SQL uses row_number functions for paging

Source: Internet
Author: User

Sql:

?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 CREATE PROCEDURE PagingViewTest (    @currentPageIndex INT, --页序号    @pageSize INT, --页大小    @pageCount INT OUTPUT--返回值,总记录数 ) AS BEGIN<br>--取总记录数 SELECT @pageCount=COUNT(OrderID) FROM dbo.sale_Order; --利用CTE以提高执行效率 WITH Result AS (    SELECT ROW_NUMBER() OVER(ORDER BY OrderID) AS rowNumber,* FROM sale_order s ) SELECT * FROM Result r WHERE ((@currentPageIndex-1)*@pageSize < rowNumber)   AND (rowNumber <[email protected]*@pageSize) END

Execution Result:

has always wanted to implement the paging of the stored procedures, has not been realized, today is not lazy, to the point, briefly explain the principle of the next page: pagination has several parameters, the current page number (that is, the number of pages, must), the page size (display quantity per page, must), total pages (optional), total records (optional) The foreground query data requires at least two required parameters to be sent back to the station. With the parameters, SQL Server will not worry about paging! The main reason for using Row_number is to number the table to determine that the records in the table are the X-page data, and the table that executes the Row_number function is as follows:

See RowNumber column believe everyone has the idea, just add where condition previous page * per page size < RowNumber and. RowNumber <= Current Page * Each page size can be, the principle is these, you can continue to expand based on this idea, such as the introduction of table names to implement a common table or view paging and so on.

Today about SQL paging is introduced here, you are welcome to criticize correct.

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.