SQL paging stored procedures support connection queries and other complex SQL statements

Source: Internet
Author: User
CREATEPROCEDUREPagination (& nbsp; @ SQLnvarchar (1024), & nbsp; @ PageSizeint20, & nbsp; -- page size & nbsp; @ PageIndexint0, & nbsp; -- paging index & nbsp; @ Sortnvarc create procedure Pagination
(
@ SQL nvarchar (1024 ),
@ PageSize int = 20, -- page size
@ PageIndex int = 0, -- paging Index
@ Sort nvarchar (100) = ''', -- Sort Field
@ TotalCount int = 0 output -- total
)
AS

Set nocount on
/* Declare the query string */
Declare @ strSQL nvarchar (4000)

Set @ strSQL = ''select @ TotalCount = count (*) from () as t''

/* Total Number of query results obtained */
Exec sp_executesql
@ StrSQL,
Int = 0 OUTPUT '',
@ TotalCount = @ TotalCount OUTPUT

Declare @ ItemCount int
Declare @ _ PageIndex int

Set @ _ PageIndex = @ PageIndex + 1;
/* Determine the search boundary */
Set @ ItemCount = @ TotalCount-@ PageSize * @ _ PageIndex

If (@ ItemCount <0)
Set @ ItemCount = @ ItemCount + @ PageSize
Else
Set @ ItemCount = @ PageSize

If (@ ItemCount <0) return 1

If (@ Sort! = '''')
Begin
/* Declare the sorting variable */
Declare @ IndexSort1 nvarchar (50), @ IndexSort2 nvarchar (50), @ Sort1 nvarchar (50), @ Sort2 nvarchar (50)

SET @ Sort1 = @ Sort
SET @ Sort2 = Replace (@ Sort, ''desc'',), ''asc '', ''desc ''),, ''asc '')

Print @ Sort1
Print @ Sort2

Set @ strSQL = ''SELECT * FROM
(Select top ''+ STR (@ ItemCount) + ''' * FROM
(Select top ''+ STR (@ PageSize * @ _ PageIndex) + ''' * FROM
() AS t0
Order by + '') AS t1
Order by + '') AS t2
Order''
End
Else
Begin
Set @ strSQL = ''SELECT * FROM
(Select top ''+ STR (@ ItemCount) </

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.