我的sql資料庫儲存過程分頁

2022-02-23 07:07:54 字數 1580 閱讀 4171

tag: 資料庫

儲存過程

分頁sql

以前用到資料庫儲存過程分頁的時候都是用 not in

但是最近工作的時候,隨著資料庫記錄的不斷增大,發現not in的效率 真的不行

雖然都設定了索引,但是當記錄達到10w的時候就發現不行了,都是需要好幾秒鐘,受不了了

所以就想換個方法,直接找到需要的頁面的資料庫記錄的第乙個id,當然這個id是有索引,唯一的

而且是主鍵,這個也是網上說到的最快的乙個方法 ^_^,據說比游標更快(我沒用過游標)

create procedure sp_image_list_bycategoryid3

(@rowscount int =0 output,

@categoryid int,

@currentpage int =1,

@pagesize int = 20 )as

declare  @sql nvarchar(2000)

set @sql  =  ''

select @rowscount=count(imageid) from  t_images where categoryid=@categoryid

if  @currentpage = 1

set  @sql = @sql + 'select top ' + cast(@pagesize as nvarchar(20)) + ' imageid,thumbname,imagecode,bigcategoryid  from t_images where categoryid=' + cast(@categoryid as varchar(10))+' order by imageid desc '

else

begin

declare  @num int

set  @num = @pagesize * (@currentpage - 1)

set  @sql = @sql + 'declare  @lastid nvarchar(100)' + char(13)

set  @sql = @sql + 'select top ' + cast(@num as nvarchar(20)) + ' @lastid= imageid from t_images where categoryid=' + cast(@categoryid as varchar(10))+'  order by imageid desc ' + char(13)

set  @sql = @sql + 'select top ' + cast(@pagesize as nvarchar(20)) + '  imageid,thumbname,imagecode,bigcategoryid  from t_images where categoryid=' + cast(@categoryid as varchar(10))+'   and imageid < @lastid  order by imageid desc '

endexecute sp_executesql @sql

go換了這個儲存過程過程後,發現真的快了很多,現在的資料是40w,就是檢索最後一頁,都只需要100多ms,爽多了,^_^,我的imageid上面做了 聯合索引 呵呵

資料庫端分頁儲存過程

近日專案中要用到大批量的資料分頁顯示,而vs2003中的datagrid中的分頁機制是整個的讀出資料到記憶體,再將記憶體中符合分頁條件的資料顯示到頁面,如果資料量達到一定程式會占用大量系統資源,導致整個程式反應遲鈍。因而只好採用在資料庫端分頁的方法,每次只讀出指定的記錄數。create proced...

資料庫非儲存過程分頁

oracle中的分頁 select from select a.rownum rc from 表名 where rownum endrow a where a.rc startrow select a1.from select student.rownum rn from student a1 wh...

MSSQL MySQL 資料庫分頁 儲存過程

先看看單條 sql 語句的分頁 sql 吧。方法1 適用於 sql server 2000 2005 複製 如下 select top 頁大小 from table1 where id not in select top 頁大小 頁數 1 id frwww.cppcns.comom table1 o...