SQL Server資料庫分頁查詢

2021-09-25 06:51:41 字數 2063 閱讀 4646

一、建立表結構

create table [dbo].[a](

[id] [int] not null,

[name] [nvarchar](50) null,

[age] [int] null)

二、新增測試資料

declare @i int

set @i=1

while(@i<10000)

begin

insert into a select @i,left(newid(),7),12

set @i += 1

end

三、分頁sql,下面例子是每頁10條,取第31-40條資料。

--方法一:order by

select top (40-31+1) * from a where id in (select top 40 id from a order by id ) order by id desc

--方法二:not in/top

select top 10 * from a where id not in (select top 30 id from a order by id) order by id

--方法三:not exists

select top 10 * from a where not exists (select 1 from (select top 30 id from a order by id)a1 where a1.id=a.id) order by id

--方法四:max/top

select top 10 * from a where id>(select max(id) from (select top 30 id from a order by id)a1) order by id

--方法五:row_number()

select top 10 * from (select row_number()over(order by id)rownumber,* from a)a1 where rownumber>30

select * from (select row_number()over(order by id)rownumber,* from a) a1 where rownumber>30 and rownumber<41

select * from (select row_number()over(order by id)rownumber,* from a)a1 where rownumber between 31 and 40

--方法六:row_number() 變體,不基於已有字段產生記錄序號,先按條件篩選以及排好序,再在結果集上給一常量列用於產生記錄序號

select *

from (select row_number()over(order by id)rownumber,* from (select top 40 * from a where 1=1 order by id)a

)b where rownumber>30

四、sql語句效率測試

declare @begin_date datetime

declare @end_date datetime

select @begin_date = getdate()

<.....your code.....>

select @end_date = getdate()

select datediff(ms,@begin_date,@end_date) as '毫秒'

1萬:基本感覺不到差異

10萬:

五、結論

1.max/top,row_number()都是比較不錯的分頁方法。相比row_number()只支援sql2005及以上版本,max/top有更好的可移植性,能同時適用於sql2000,access。

2.not exists感覺是要比not in效率高一點點。

3.row_number()的3種不同寫法效率看起來差不多。

資料庫分頁查詢(sql server)

程式如下 alter proc pageing pageindex int,頁索引 pagesize int 每頁幾條 asselect empno,ename,job,isnull mgr,0 sal,isnull hiredate,getdate isnull comm,0 isnull dep...

幾種SQL Server資料庫分頁方式

photosprite 建立表 create table testtable id int identity 1,1 not null firstname nvarchar 100 collate chinese prc ci as null lastname nvarchar 100 collat...

SQL Server 資料庫增刪改查

sql server 資料庫 新增字段 alter table 表名 add 欄位名 varchar 50 null 修改字段 execute sp rename 表名.原欄位名 新欄位名 刪除字段 alter table 表名 drop column 欄位名 表中新增自增id alter tabl...