欢迎光临
我们一直在努力

SQL Server 存储过程的分页-ASP教程,数据库相关

建站超值云服务器,限时71元/月

建立表:

create table [testtable] (
[id] [int] identity (1, 1) not null ,
[firstname] [nvarchar] (100) collate chinese_prc_ci_as null ,
[lastname] [nvarchar] (100) collate chinese_prc_ci_as null ,
[country] [nvarchar] (50) collate chinese_prc_ci_as null ,
[note] [nvarchar] (2000) collate chinese_prc_ci_as null
) on [primary]
go

插入数据:(2万条,用更多的数据测试会明显一些)
set identity_insert testtable on

declare @i int
set @i=1
while @i<=20000
begin
insert into testtable([id], firstname, lastname, country,note) values(@i, firstname_xxx,lastname_xxx,country_xxx,note_xxx)
set @i=@i+1
end

set identity_insert testtable off

————————————-

分页方案一:(利用not in和select top分页)
语句形式:
select top 10 *
from testtable
where (id not in
(select top 20 id
from testtable
order by id))
order by id

select top 页大小 *
from testtable
where (id not in
(select top 页大小*页数 id
from 表
order by id))
order by id

————————————-

分页方案二:(利用id大于多少和select top分页)
语句形式:
select top 10 *
from testtable
where (id >
(select max(id)
from (select top 20 id
from testtable
order by id) as t))
order by id

select top 页大小 *
from testtable
where (id >
(select max(id)
from (select top 页大小*页数 id
from 表
order by id) as t))
order by id

————————————-

分页方案三:(利用sql的游标存储过程分页)
create procedure xiaozhengge
@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

其它的方案:如果没有主键,可以用临时表,也可以用方案三做,但是效率会低。
建议优化的时候,加上主键和索引,查询效率会提高。

通过sql 查询分析器,显示比较:我的结论是:
分页方案二:(利用id大于多少和select top分页)效率最高,需要拼接sql语句
分页方案一:(利用not in和select top分页) 效率次之,需要拼接sql语句
分页方案三:(利用sql的游标存储过程分页) 效率最差,但是最为通用

在实际情况中,要具体分析。

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » SQL Server 存储过程的分页-ASP教程,数据库相关
分享到: 更多 (0)