sql server分页查询代码三种方案对比

发布时间:2020-11-15编辑:脚本学堂
有关sql server数据库分页查询的三种方案,sql数据库分页代码的三个例子,对研究sql server大数据分页很有帮助。

通过实例学习sql server数据库是如何分页查询数据的。

首先,建立表:
 

复制代码 代码示例:
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
 

 
以下是三种分页查询的方案,大家对比下,这里推荐第一种sql分页代码

分页方案1:(利用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

分页方案2:(利用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

分页方案3:(利用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