分页存储过程(用存储过程实现数据库的分页代码)

复制代码 代码如下:

–*******************************************************

–* 分页存储过程 *

–* 撒哈拉大森林 *

–* 2010-6-28 *

–*******************************************************

if exists(select * from sysobjects where type=’p’ and name=n’p_paging’)

drop procedure p_paging

go

create procedure p_paging

@sqlstr nvarchar(4000), –查询字符串

@currentpage int, –第n页

@pagesize int –每页行数

as

set nocount on

declare @p1 int, –p1是游标的id

@rowcount int

exec sp_cursoropen @p1 output,@sqlstr,@scrollopt=1,@ccopt=1,@rowcount=@rowcount output

select ceiling(1.0*@rowcount/@pagesize) as 总页数–,@rowcount as 总行数,@currentpage as 当前页

set @currentpage=(@currentpage-1)*@pagesize+1

exec sp_cursorfetch @p1,16,@currentpage,@pagesize

exec sp_cursorclose @p1

set nocount off

go

—-创建测试表

–if exists(select * from sysobjects where type=’u’ and name=n’test_students’)

— drop table test_students

–go

–create table test_students(

— id int identity(1,1) not null,

— name nvarchar(100) not null

–)



—-创建测试数据

–declare @i int

–set @i = 100000

–while @i>0

— begin

— insert into test_students values(‘姓名’)

— set @i = @i – 1

— end



—-执行存储过程

–exec p_paging ‘select * from test_students order by id’,100,100 –执行



—-删除测试表

–if exists(select * from sysobjects where type=’u’ and name=n’test_students’)

— drop table test_students

–go

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐