General paging stored procedure (SQL Server 2005)

Source: Internet
Author: User
The code is as follows: Copy code

 

If object_ID ('[proc_SelectForPager]') is not null
Drop Procedure [proc_SelectForPager]
Go
Create Proc proc_SelectForPager
(
@ SQL varchar (max ),
@ Order varchar (4000 ),
@ CurrentPage int,
@ PageSize int,
@ TotalCount int output
)
As
/* Andy 2012-2-28 */
Declare @ Exec_ SQL nvarchar (max)
               
Set @ Exec_ SQL = 'set @ TotalCount = (Select Count (1) From ('+ @ SQL +') As )'
Exec sp_executesql @ Exec_ SQL, n' @ TotalCount int output', @ TotalCount output
 
Set @ Order = isnull ('Order by' + nullif (@ Order, ''), 'Order by getdate ()')
 
If @ CurrentPage = 1/* the 1st page is often called. Special processing is performed here, with a lower layer of subquery */
Set @ Exec_ SQL ='
; With CTE_Exec
    (
'+ @ SQL +'
    )
Select Top (@ pagesize) *, row_number () Over ('+ @ Order +') As r From CTE_Exec Order By r
    '
Else
Set @ Exec_ SQL ='
; With CTE_Exec
    (
Select *, row_number () Over ('+ @ Order +') As r From ('+ @ SQL +') As
    )
Select * From CTE_Exec Where r Between (@ CurrentPage-1) * @ pagesize + 1 And @ CurrentPage * @ pagesize Order By r
    '
 
 
Exec sp_executesql @ Exec_ SQL, n' @ CurrentPage int, @ PageSize int ', @ CurrentPage, @ PageSize
 
Go

Call method:

1. Single table:

The code is as follows: Copy code

Exec proc_SelectForPager @ SQL = 'select * from contacts a where a. ContactType = 1', -- varchar (max)
@ Order = '', -- varchar (4000)
@ CurrentPage = 3, -- int
@ PageSize = 20, -- int
@ TotalCount = 0 -- int2. multi-table join:


Exec proc_SelectForPager @ SQL =
'Select a. Staff, a. OU, B. FName + B. FName as Name
From staffOUHIST
Inner join Staff B on B. ID = a. Staff and a. ExpiryDate = '20180101''
', -- Varchar (max)
@ Order = '', -- varchar (4000)
@ CurrentPage = 3, -- int
@ PageSize = 20, -- int
@ TotalCount = 0 -- int

Note: CTE cannot be used in @ SQL.

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.