>데이터 베이스 >MySQL 튜토리얼 >通用分页存储过程(SQL Server 2005)

通用分页存储过程(SQL Server 2005)

WBOY
WBOY원래의
2016-06-07 17:49:19898검색

这是不久前写的一个分页存储过程,可应用于SQL Server 2005上面:

 代码如下 复制代码

 

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 /*经常会调用第1页,这里做特殊处理,少一层子查询*/
    Set @Exec_sql='
    ;With CTE_Exec As
    (
        '+@Sql+'
    )
    Select Top(@pagesize) *,row_number() Over('+@Order+') As r From 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

调用方法:

1.单表:

 代码如下 复制代码

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.多表联接:


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 = 20, -- int
        @TotalCount = 0 -- int

注:在@Sql 中不能使用CTE。

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.