MSSQL paging: the fastest row_number () over paging Stored Procedure for querying the first few pages

Source: Internet
Author: User
Code

  Create     Procedure     [  DBO  ]  .  [  Getpagerrowover  ]   
@ Pageindex Int = 1 ,
@ Pagesize Int = 10 ,
@ Tables Nvarchar ( 1000 ) = Null ,
@ Fields Nvarchar ( 2000 ) = ' * ' ,
@ Where Nvarchar ( 2000 ) = Null ,
@ Groupby Nvarchar ( 2000 ) = Null ,
@ Orderby Nvarchar ( 1000 ) = Null ,
@ Returncount Int = 0 Output
As
Begin
Set Nocount On ;
Declare @ SQL Nvarchar ( 4000 ), @ Startrowindex Int , @ Maximumrows Int ;
Declare @ Strwhere Nvarchar ( 2000 )
Declare @ Strgroupby Nvarchar ( 2000 )

Set @ Startrowindex = ( @ Pageindex - 1 ) * @ Pagesize ;
Set @ Maximumrows = @ Pagesize ;

If @ Where Is Not Null And @ Where ! = ''
Begin
Set @ Strwhere = ' Where ' + @ Where
End
Else
Begin
Set @ Strwhere = ''
End
If @ Groupby Is Not Null And @ Groupby ! = ''
Begin
Set @ Strgroupby = ' Group ' + @ Groupby
End
Else
Begin
Set @ Strgroupby = ''
End

Set @ SQL = ' Select ' + @ Fields + ' From (select ' + @ Fields + ' , Row_number () over (order ' + @ Orderby + ' ) As rownum from ' + @ Tables + @ Strwhere + @ Strgroupby + ' ) As tmptable where rownum> ' + Convert ( Nvarchar ( 10 ), @ Startrowindex ) + ' And rownum <= ( ' + Convert ( Nvarchar ( 10 ), @ Startrowindex ) + ' + ' + Convert ( Nvarchar ( 10 ), @ Maximumrows ) + ' ) '
Exec ( @ SQL )
Print @ SQL
Set @ SQL = ' Select @ returncount = count (*) from ' + @ Tables + @ Strwhere
Exec Sp_executesql @ SQL , N ' @ Returncount int output ' , @ Returncount Output
Print @ SQL
End

 

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.