利用游标写存储过程

本文介绍了如何在SQL中利用滚动游标(scroll cursor)来编写存储过程,以实现分页查询。首先定义并初始化变量,然后声明一个按ID降序排列的游标。接着,根据输入的页面大小和页码计算总页数,并检查页码的有效性。通过游标定位到起始和结束记录,最后返回所需页码范围内的记录。

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

declare @startindex int,@endindex int,@totalrecord int,@current_startindex int,@current_endindex int
--定义几个变量

declare cur_book_page scroll cursor for
select id from bookclass order by id desc
--定义一个滚动游标
open cur_book_page
--打开游标

set @totalrecord = @@cursor_rows
--得到总的记录数

if @totalrecord > 0
begin
if @totalrecord % @pagesize = 0
set @pagetotal = @totalrecord / @pagesize
else
set @pagetotal = @totalrecord / @pagesize + 1
--得到总页数

if @pageindex < 1
set @pageindex = 1

if @pageindex > @pagetotal
set @pageindex = @pagetotal
--检查输入参数,确保它在1到总页数之间

set @startindex = (@pageindex-1)*@pagesize+1
--游标第一次移动到的位置,比如我们需要第10到15条记录,那么这个参数的值是11

set @endindex = @pageindex*@pagesize
--游标第二次移动到的位置,如上,这个值应该是15

if @endindex > @totalrecord
set @endindex = @totalrecord
--确保第二次移动不超过记录的总条数

fetch absolute @startindex from cur_book_page
into @current_startindex
--移动游标,得到第11条记录的Id,存储在参数中
fetch absolute @endindex from cur_book_page
into @current_endindex
--移动游标,得到第15条记录的Id,存储在参数中

select * from bookclass where id between @current_endindex and @current_startindex order by id desc
--得到所需的记录。注意id排列的顺序,确保between 小id and 大id,在本例中是倒序排列,所以@current_startindex是小于@current_endindex的
end
else
begin
set @pagetotal = 0
select top 0 * from bookclass
end

close cur_book_page
--关闭游标
deallocate cur_book_page
--释放游标
GO 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值