欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

SQL Server 2005通用分页存储过程及多表联接应用

程序员文章站 2022-06-04 23:11:50
这是不久前写的一个分页存储过程,可应用于sql server 2005上面: 复制代码 代码如下: if object_id('[proc_selectforpager]'...
这是不久前写的一个分页存储过程,可应用于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。