SQL Server paging stored procedure

Source: Internet
Author: User
Tags rowcount

SQL Server paging stored procedure

CREATE proc [dbo]. [Proc_opinion_baseinfo]

@TableName varchar (4000),

@PkField varchar (100),

@PageIndex Int=1,

@PageSize int=10,

@SqlWhere nvarchar (4000),

@RowCount bigint OUTPUT,

@PageCount bigint output

As

if (@SqlWhere = ' 1 ')

Set @SqlWhere = ' 1=1 '

declare @sql nvarchar (4000), @start int, @end int

Set @sql = ' SELECT * FROM (select Row_number () + @PkField + ' desc] rowid,* from ' + @TableName + ' where ' + @SqlWher E

Set @start = (@PageIndex-1) * @PageSize +1

Set @end = @start + @PageSize-1

Set @sql = @sql + ') t where rowId between ' +cast (@start as varchar) + ' and ' +cast (@end as varchar (20))

EXEC (@sql)

Set @sql = ' Select @RowCount =count (1) from ' + @TableName + ' where ' + @SqlWhere

EXEC sp_executesql @sql, N ' @RowCount bigint output ', @RowCount output

if (@RowCount% @PageSize =0)

Begin

Set @PageCount = @RowCount/@PageSize

End

Else

Begin

Set @PageCount = @RowCount/@PageSize +1

End

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.