A common paging Stored Procedure Code Based on ROW_NUMBER ()

Source: Internet
Author: User

After the following stored procedure is created, you can directly call the stored procedure by page.
Note: If the data volume is large and the performance requirement is high, please customize the processing.
Copy codeThe Code is as follows:
Alter procedure [dbo]. [COMMON_PROCEDURE_SelectWithPage]
@ SQL VARCHAR (5000 ),
@ CurrentPageNo INT,
@ PageSize INT,
@ TotalNum INT OUTPUT
AS
SET NOCOUNT ON
DECLARE @ SqlCmd VARCHAR (5000)
---------------------------------------- -- Query data
SET @ SqlCmd = 'select * FROM ('+ @ SQL +') A WHERE RowIndex BETWEEN '+ CONVERT (VARCHAR, (@ CurrentPageNo-1) * @ PageSize + 1) + 'and' + CONVERT (VARCHAR, @ CurrentPageNo * @ PageSize)
EXEC (@ SqlCmd) PRINT (@ SqlCmd)
---------------------------------------- -- Calculate the total number of records
IF @ TotalNum =-1
BEGIN
Create table # Temp1 (num INT)
Insert into # Temp1
EXEC ('select count (*) FROM ('+ @ SQL +') ')
SELECT @ TotalNum = (SELECT * FROM # Temp1)
Drop table # Temp1
END

The usage is simple, but ROW_NUMBER () OVER (...) AS RowIndex must be used in the passed SQL statement:
DECLARE @ SQL VARCHAR (5000)
DECLARE @ CurrentPageNo INT
DECLARE @ PageSize INT
DECLARE @ TotalNum INT

SET @ CurrentPageNo = 100
SET @ PageSize = 10
SET @ TotalNum =-1
SET @ SQL = 'select *, ROW_NUMBER () OVER (ORDER BY sorting field) AS RowIndex FROM table name A WITH (NOLOCK )'

EXEC [dbo]. [COMMON_PROCEDURE_SelectWithPage] @ SQL, @ CurrentPageNo, @ PageSize, @ TotalNum OUTPUT

SELECT @ TotalNum

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.