create procedure sp_page
@tb varchar(50), --表名
@col varchar(50), --按该列来进行分页
@coltype int, [email protected]列的类型,0-数字类型,1-字符类型,2-日期时间类型
@orderby bit, --排序,0-顺序,1-倒序
@collist varchar(800),--要查询出的字段列表,*表示全部字段
@pagesize int, --每页记录数
@page int, --指定页
@condition varchar(800),--查询条件
@pages int output --总页数
as
/*
功能描述:对指定表中满足条件的记录按指定列进行分页查询,分页可以顺序、倒序
查询可以指定页大小、指定查询任意页、指定输出字段列表,返回总页数
作 者:pbsql
版 本:1.10
最后修改:2004-11-29
*/
declare @sql nvarchar(4000),@where1 varchar(800),@where2 varchar(800)
if @condition is null or rtrim(@condition)=''
begin--没有查询条件
set @where1=' where '
set @where2=' '
end
else
begin--有查询条件
set @where1=' where ('[email protected]+') and '--本来有条件再加上此条件
set @where2=' where ('[email protected]+') '--原本没有条件而加上此条件
end
set @sql='select @pages=ceiling((count(*)+0.0)/'+cast(@pagesize as varchar)+
') from '[email protected][email protected]
exec sp_executesql @sql,n'@pages int output',@pages output--计算总页数
if @orderby=0
set @sql='select top '+cast(@pagesize as varchar)+' '[email protected]+
' from (select">'[email protected][email protected][email protected]+'>(select max('[email protected]+') '+
' from (select top '+cast(@pagesize*(@page-1) as varchar)+' '+
@col+' from '[email protected][email protected]+'order by '[email protected]+') t) order by '[email protected]
else
set @sql='select top '+cast(@pagesize as varchar)+' '[email protected]+
' from '[email protected][email protected][email protected]+'<(select min('[email protected]+') '+
' from (select top '+cast(@pagesize*(@page-1) as varchar)+' '+
@col+' from '[email protected][email protected]+'order by '[email protected]+' desc) t) order by '+
@col+' desc'
if @page=1--第一页
set @sql='select top '+cast(@pagesize as varchar)+' '[email protected]+' from '[email protected]+
@where2+'order by '[email protected]+case @orderby when 0 then '' else ' desc' end
exec(@sql)
go
本存储过程高效,曾用500万条数据测试(已建索引),只返回分页只需3秒,影响效率的地方是计算总页数,若不需要可以注释掉
--测试示例
declare @pages int
select identity(int,1,1) id,getdate() dt,xx=cast('' as varchar(10)) into #t
from sysobjects
update #t set dt=dateadd(day,id-200,dt),
xx='xxxx'+right('000000'+cast(id as varchar(10)),6)
exec sp_page '#t','id',0,0,'*',10,2,'',@pages output--按id顺序取第二页
exec sp_page '#t','id',0,1,'*',10,2,'',@pages output--按id倒序取第二页
exec sp_page '#t','xx',1,0,'*',10,3,'',@pages output--按xx顺序取第三页
exec sp_page '#t','xx',1,1,'*',10,3,'',@pages output--按xx倒序取第三页
exec sp_page '#t','dt',2,0,'*',10,2,'',@pages output--按dt顺序取第二页
exec sp_page '#t','dt',2,1,'*',10,2,'',@pages output--按dt倒序取第二页
select 总页数[email protected]
drop table #t