通用分页存储过程(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 -- int

2.多表联接:

复制代码
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。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值