SQL Server 儲存過程的分頁

2021-04-08 19:25:41 字數 3363 閱讀 2395

建立表: 

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萬條,用更多的資料測試會明顯一些) 

setidentity_insert

testtable 

ondeclare

@iint

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

endset

identity_insert

testtable 

off--

----------------------------------- 

分頁方案一:(利用not in和select top分頁) 

語句形式: 

select

top10

*from

testtable 

where

(id 

notin

(select

top20

id from

testtable 

order

byid)) 

order

byid 

select

top頁大小 

*from

testtable 

where

(id 

notin

(select

top頁大小

*頁數 id 

from

表 order

byid)) 

order

byid 

------------------------------------- 

分頁方案二:(利用id大於多少和select top分頁) 

語句形式: 

select

top10

*from

testtable 

where

(id 

>

(select

max(id) 

from

(select

top20

id from

testtable 

order

byid) 

ast)) 

order

byid 

select

top頁大小 

*from

testtable 

where

(id 

>

(select

max(id) 

from

(select

top頁大小

*頁數 id 

from

表 order

byid) 

ast)) 

order

byid 

------------------------------------- 

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

create

procedure

xiaozhengge 

@sqlstr

nvarchar

(4000

), --

查詢字串 

@currentpage

int, 

--第n頁 

@pagesize

int--

每頁行數 

asset

nocount 

ondeclare

@p1int

, --

p1是游標的id 

@rowcount

intexec

sp_cursoropen 

@p1output,

@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 

@p1set

nocount 

off其它的方案:如果沒有主鍵,可以用臨時表,也可以用方案三做,但是效率會低。 

建議優化的時候,加上主鍵和索引,查詢效率會提高。 

通過sql 查詢分析器,顯示比較:我的結論是: 

分頁方案二:(利用id大於多少和select top分頁)效率最高,需要拼接sql語句 

分頁方案一:(利用not in和select top分頁) 效率次之,需要拼接sql語句 

分頁方案三:(利用sql的游標儲存過程分頁) 效率最差,但是最為通用 

在實際情況中,要具體分析。

SQLserver的儲存過程

儲存過程 create 是建立儲存過程,alter 是更改 改變儲存過程 在第一次寫儲存過程時用 create 若修改儲存過程程式之後,則 alter 替換create 再執行 在資料庫中 begin end 為大括號的意思 建立儲存過程的格式 procedure可簡寫為proc proc為程式 步...

sql server儲存過程

建立表的語句 create table student sno int primary key,sname nvarchar 30 sgentle nvarchar 2 sage int,sbirth smalldatetime,sdept nvarchar 30 drop table studen...

SQLSERVER儲存過程

sqlserver儲存過程使用說明書 引言首先介紹一下什麼是儲存過程 儲存過程就是將常用的或很複雜的工作,預先用 sql語句寫好並用乙個指定的名稱儲存起來,並且這樣的語句是放在資料庫中的,還可以根據條件執行不同 sql語句,那麼以後要叫資料庫提供與已定義好的儲存過程的功能相同的服務時,只需呼叫 ex...