SQL Server 2005 Common paging stored procedures and multiple table join applications _mssql2005

Source: Internet
Author: User
This is a recently written paging stored procedure that can be applied to SQL Server 2005:
Copy Code code as follows:

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 a) '
Exec sp_executesql @Exec_sql, N ' @TotalCount int output ', @TotalCount output
Set @Order =isnull (' ORDER by ' +nullif (@Order, "), ' Order by GETDATE () ')
If @CurrentPage = 1/* will often call page 1th, here to do special processing, less a layer of subquery * *
Set @Exec_sql = '
; With Cte_exec as
(
' + @Sql + '
)
Select Top (@pagesize) *,row_number () over (' + @Order + ') as R-Cte_exec order by R
'
Else
Set @Exec_sql = '
; With Cte_exec as
(
Select *,row_number () over (' + @Order + ') as r from (' + @Sql + ') as a
)
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
Copy Code code as follows:

Exec Proc_selectforpager @Sql = ' Select * from contacts a where a.contacttype=1 ',-varchar (max)
@Order = ",--varchar (4000)
@CurrentPage = 3,--int
@PageSize =--INT
@TotalCount = 0--int

2. Multi-table Join
Copy Code code as follows:

Exec Proc_selectforpager @Sql =
' Select A.staff,a.ou,b.fname+b.fname as Name
From Staffouhist A
INNER JOIN Staff B on B.id=a.staff and a.expirydate= ' 30001231 '
',--varchar (max)
@Order = ",--varchar (4000)
@CurrentPage = 3,--int
@PageSize =--INT
@TotalCount = 0--int

Note: You cannot use a CTE 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.