特殊分页处理

博客给出了数据库分页处理的示例,包含测试数据的创建、分页处理存储过程的编写及调用,分页要求为每页5条记录,c类2条、b类1条、a类2条,数据按uptime降序、grade=c>b>a、id降序排列,某类不足时由后续类补齐,最后还进行了测试数据和存储过程的删除。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原帖地址:
http://community.youkuaiyun.com/Expert/topic/3662/3662135.xml?temp=.4289972

--测试数据
create table tb(ID int primary key,grade varchar(10),uptime datetime)
insert tb select 1 ,'a','2004-12-11'
union all select 2 ,'b','2004-12-11'
union all select 3 ,'c','2004-12-11'
union all select 4 ,'a','2004-12-12'
union all select 5 ,'c','2004-12-13'
union all select 6 ,'c','2004-12-13'
union all select 7 ,'a','2004-12-14'
union all select 8 ,'a','2004-12-15'
union all select 9 ,'b','2004-12-16'
union all select 10,'b','2004-12-17'
union all select 11,'a','2004-12-17'
go

/*--分页处理要求

每页5条记录: c类2条 b类1条 a类2条
数据顺序,uptime desc,grade=c>b>a,id desc
某类不足时,由它的后续类补齐
--*/

--分页处理的存储过程
create proc p_split
@currentpage int=1, --要显示的当前页
@pagesize int=5 --每页的大小(如果调整了这个,则存储过程中,排序的处理也要做相应的修改,即:case grade when 'c' then 2 when 'b' then 1 when 'a' then 2 end 部分,这个控制每类/每页多少条记录as
set nocount on
set @currentpage=@currentpage*@pagesize
set rowcount @currentpage
select * into #t from tb a
order by ((select count(*) from tb where grade=a.grade and(uptime>a.uptime or uptime=a.uptime and id>=a.id))-1)
/case grade when 'c' then 2 when 'b' then 1 when 'a' then 2 end
,case grade when 'c' then 1 when 'b' then 2 when 'a' then 3 end,id desc
if @currentpage>@pagesize
begin
set @currentpage=@currentpage-@pagesize
set rowcount @currentpage
delete from #t
end
select * from #t
order by case grade when 'c' then 1 when 'b' then 2 when 'a' then 3 end
,uptime desc,id desc
go

--调用
exec p_split 1
exec p_split 2
exec p_split 3
go

--删除测试
drop table tb
drop proc p_split

/*--测试结果

ID grade uptime
----------- ---------- -------------------------
6 c 2004-12-13 00:00:00.000
5 c 2004-12-13 00:00:00.000
10 b 2004-12-17 00:00:00.000
11 a 2004-12-17 00:00:00.000
8 a 2004-12-15 00:00:00.000


ID grade uptime
----------- ---------- -------------------------
3 c 2004-12-11 00:00:00.000
9 b 2004-12-16 00:00:00.000
2 b 2004-12-11 00:00:00.000
7 a 2004-12-14 00:00:00.000
4 a 2004-12-12 00:00:00.000


ID grade uptime
----------- ---------- -------------------------
1 a 2004-12-11 00:00:00.000
--*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值