Sql2005 stored procedure pagination sample code _mssql

Source: Internet
Author: User
Tags stored procedure example
Copy Code code as follows:

--Pagination Stored Procedure example
Alter PROCEDURE [dbo]. [Jh_pagedemo]
@pageSize int = 9000000000,
@pageIndex int = 1,
@orderBy Nvarchar (200) = '--without order by
As
SET NOCOUNT on
--Declaring variables
DECLARE @select VARCHAR (3048);
DECLARE @from VARCHAR (512);
DECLARE @RowNumber VARCHAR (256);
DECLARE @condition NVARCHAR (3990);
DECLARE @groupBy varchar (50);
DECLARE @sql VARCHAR (3998);
DECLARE @RowStartIndex INT;
DECLARE @RowEndIndex INT;
BEGIN
SET NOCOUNT on
IF @orderBy <> '
Set @orderBy = ' ORDER by ' + @orderBy;
Else
Set @orderBy = ' ORDER by Userid ';
SET @select = ' select Userid,username, ';
--Set Sort statements
SET @RowNumber = ' row_number () over (' + @orderBy + ') as RowNumber ';
SET @select = @select + @RowNumber;
SET @from = ' from users ';
--Set Conditional statement @gulevel
SET @condition = ' WHERE 1=1 ';
SET @condition = @condition + ' and userid > 0 ';
--Grouped statements
SET @groupBy = ' GROUP by USerID '
SET @RowStartIndex = (@pageIndex-1) * @pageSize + 1
SET @RowEndIndex = @pageIndex * @pageSize;
--Query results
Set @sql = ' Set NOCOUNT on;
With Resulttable as (' + @select + @from + @condition + ')
SELECT * from resulttable WHERE rownumber between ' +
Cast (@RowStartIndex as VARCHAR) + ' and ' + cast (@RowEndIndex as VARCHAR (32))
+ ' ; SELECT Count (*) as TotalCount ' + @from + @condition + '

--print @sql;
EXEC (@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.