SQL Server 數據分頁

一、建立表sql

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
)

二、寫入測試數據ide

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

三、利用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

四、分頁查詢的方法spa

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
相關文章
相關標籤/搜索