幾種SQL Server資料庫分頁方式

2021-09-05 18:36:00 字數 2484 閱讀 6950

photosprite

-- 建立表 --

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 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_***', 'lastname_***', 'country_***', 'note_***')

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 表

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

) t)

) order by id

/*  方法

select top 頁大小 *

from 表

where (id > (

select max(id)

from (

select top 頁大小*頁數 id

from 表

order by id

) t)

) order by id

*/-- 分頁方案三:(利用sql的游標儲存過程分頁)

create procedure sp_pagination

@sql nvarchar(4000), --查詢字串

@currentpage int, --第n頁

@pagesize int --每頁行數

as set nocount on

declare @p1 int, --p1是游標的id

@rowcount int

exec

sp_cursoropen @p1 output, @sql, @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的游標儲存過程分頁) 效率最差,但是最為通用

SQLServer中master資料庫分析

表sysdatabases 儲存dbms中資料庫資訊 select name from sysdatabases o程式設計客棧rder by nbs程式設計客棧p name 就能得到該dbms中的資料庫資訊 表sysobjects 儲存資料庫中資料表資訊 con.changedatabase db...

SQL Server 資料庫的幾種簡單查詢

在數庫檔案內容較多的情況下,為了更加明確快速得找到某條資訊,下面舉出3種sql查詢方法 1 投影查詢 2 選擇查詢 3 排序查詢 下面給出的是進行測試的資料庫表table 首先是投影查詢,為了讓檢視的資料更加明確,易懂。投影查詢有三種寫法 select cid 客戶編號,ccontact 聯絡人,c...

SQLServer收縮資料庫

以下語句用於設定資料庫定時自動收縮資料庫 use master gosp dboption testdb,autoshrink true gouse testdb gocheckpoint go 清空日誌語句 dump transaction testdb with no log 截斷事務日誌 ba...