一个sql server2005分页的存储过程

本文介绍了一种在 SQL Server 中实现分页查询的方法。通过创建一个包含27条记录的测试表,并定义一个用于分页查询的存储过程,演示了如何按需获取指定页数的数据记录。

--sql server 分页语句

--首先创建一个测试用的表,并且插入一些测试数据

if exists (select * from sysobjects where name='test')
drop table test
go
create table test
(
id int primary key identity(1,1),
name varchar(20)
)
go
insert into test values('aaa')
insert into test values('bbb')
insert into test values('vvv')
insert into test values('fff')
insert into test values('eee')
insert into test values('ggg')
insert into test values('ddd')
insert into test values('sss')
insert into test values('ttt')
insert into test values('555')
insert into test values('uyuu')
insert into test values('vvjhgjv')
insert into test values('ffghfgdf')
insert into test values('fsdfsdf')
insert into test values('rewrew')
insert into test values('fsdfsd')
insert into test values('gfdgf')
insert into test values('ttgsdsdbt')
insert into test values('fdsfdsaf')
insert into test values('ghfdsfs')
insert into test values('vvvhgfhg')
insert into test values('fdsfsgffff')
insert into test values('eeehgfhjgf')
insert into test values('ggghgjgf')
insert into test values('dddfdsafdd')
insert into test values('sssfdsfds')
insert into test values('jhkjkjttt')
select * from test
执行结果:
idname
1 aaa
2 bbb
3 vvv
4 fff
5 eee
6 ggg
7 ddd
8 sss
9 ttt
10555
11uyuu
12vvjhgjv
13ffghfgdf
14fsdfsdf
15rewrew
16fsdfsd
17gfdgf
18ttgsdsdbt
19fdsfdsaf
20ghfdsfs
21vvvhgfhg
22fdsfsgffff
23eeehgfhjgf
24ggghgjgf
25dddfdsafdd
26sssfdsfds
27jhkjkjttt
--创建一个简单的存储过程来实现分页:
if exists (select * from sysobjects where name='proc_page')
drop proc proc_page
go
create proc proc_page
@num int=10,--此存储过程接收两个参数,第一个参数为每页显示多少条记录,默认为10 条。
@page int=1--第二个参数为显示第几页,默认为第1 页。
as
if((select count(*) from test)-(@page-1)*(@num)<=0)--判断如果超出总行数的范围则提示用户
print '已超出最大页数!请缩小要显示页号或者减少每页要显示的行数!'
else
select top (@num) * from (select top ((select count(*) from test)-((@page-1)*(@num))) * from test order by id desc) as a order by id asc
go
调用不带参数的,默认显示第一页,每页10条。
exec proc_page
go
执行结果:
idname
1 aaa
2 bbb
3 vvv
4 fff
5 eee
6 ggg
7 ddd
8 sss
9 ttt
10555
带一个参数的,每页的行数为给定的默认值10条,显示第三页。
exec proc_page @page=3
go
执行结果:
id name
21vvvhgfhg
22fdsfsgffff
23eeehgfhjgf
24ggghgjgf
25dddfdsafdd
26sssfdsfds
27jhkjkjttt
测试超出范围的,一共27条,这里想要显示的是3140条记录,所以提示错误了。
exec proc_page @page=4
go
执行结果:
已超出最大页数!请缩小要显示页号或者减少每页要显示的行数!
带两个参数的,每页5条,显示第3
exec proc_page 5,3
go
执行结果:
idname
11 uyuu
12 vvjhgjv
13 ffghfgdf
14 fsdfsdf
15 rewrew
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值