SQL Server 数据分页

1、创建表

create table Table_test
(
    ID int identity(1,1) primary key,
    username nvarchar(20) not null,
    userpd nvarchar(20) not null,
    useremail nvarchar(500) null
)

2、写入测试数据

set identity_insert Table_test on 
declare @count int 
set @count=1
while @count<=200000
begin 
    insert into Table_test(ID,username,userpd,useremail) values(@count,'admin','admin888','lli0077@yahoo.com.cn')
    set @count=@count+1
end

3、利用select top 和select not in进行分页

create procedure proc_paged_with_notin
(
    @pageIndex int,
    @pageSize int
)
as
begin
    set nocount on;
    declare @timediff datetime
    declare @sql nvarchar(500)
    select @timediff=Getdate()
    set @sql='select top'+str(@pageSize)+'* from Table_test where (ID not in (select top '+str(@pageSize*@pageIndex)+' id from Table_test order by ID ASC)) order by ID' 
    execute(@sql)
    select datediff(ms,@timediff,GetDate()) as 耗时
    set nocount off;
end

4、分页查询的方法

select top 20 * 
from Table_test 
where ID not in(select top (2*20) ID from Table_test order by ID asc) order by ID
select top 20 *
from Table_test
where ID>(
select max(ID) 
from (select top (2*20) ID from Table_test order by ID) as TempTable)
order by ID
原文地址:https://www.cnblogs.com/zhanghaomars/p/8191991.html