SQL分頁儲存過程

2021-04-19 19:16:45 字數 2365 閱讀 8248

create procedure prcpager

-- 獲得某一頁的資料 --

@currpage int = 1,                                 --當前頁頁碼 (即top currpage)

@showcolumn varchar(2000) = '*',        --需要得到的字段 (即 column1,column2,......)

@tabname varchar(2000),                    --需要檢視的表名 (即 from table_name)

@strcondition varchar(2000) = '',           --查詢條件 (即 where condition......) 不用加where關鍵字

@asccolumn varchar(100) = '',              --排序的欄位名 (即 order by column asc/desc)

@bitordertype bit = 0,                          ---排序的型別 (0為公升序,1為降序)

@pkcolumn varchar(50) = '',                 --主鍵名稱

@pagesize int = 20                               --分頁大小

as begin -- 儲存過程開始

-- 該儲存過程需要用到的幾個變數

declare @strsql varchar(4000)           --該儲存過程最後執行的語句

declare @strordertype varchar(1000)     --排序型別語句 (order by column asc或者order by column desc)

begin

if @bitordertype = 1   -- bitordertype=1即執行降序

begin

set @strordertype = ' order by '+@asccolumn+' desc'

end

else

begin

set @strordertype = ' order by '+@asccolumn+' asc'

end

if @currpage = 1    -- 如果是第一頁

begin

if @strcondition != ''

set @strsql = 'select top '+str(@pagesize)+' '+@showcolumn+' from '+@tabname+

' where '+@strcondition+@strordertype

else

set @strsql = 'select top '+str(@pagesize)+' '+@showcolumn+' from '+@tabname+@strordertype

end

else    -- 其他頁

begin

if @strcondition !='' 

set @strsql ='select top '+str(@pagesize)+' '+@showcolumn+' from (select top '+str(@currpage*@pagesize)+@showcolumn+' from '

+@tabname+' where ('+@strcondition+') '+@strordertype+') as temp  where '+@pkcolumn+' not in(select top '+str((@currpage-1)*@pagesize)

+' '+@pkcolumn+ ' from '+@tabname+' where ('+@strcondition+') ' +@strordertype+')'

else 

set @strsql ='select top '+str(@pagesize)+' '+@showcolumn+' from (select top '+str(@currpage*@pagesize)+@showcolumn+' from '+@tabname+@strordertype+') as temp'

+' where '+@pkcolumn+' not in(select top '+str((@currpage-1)*@pagesize)+' '+@pkcolumn+ ' from '+@tabname+@strordertype+')'

end

end

exec (@strsql)

end  -- 儲存過程結束

goprcpager 2,'*','news','','addtime',1,'newsid',15

sql 儲存過程分頁

create proc myx prpagerecordset querystr nvarchar 1000 keyfield nvarchar 200 pagesize int,pagenumber int as begin declare sqltext as nvarchar 4000 dec...

SQL 儲存過程 分頁

1.俄羅斯儲存過程 的改良版 create procedure pagination1 pagesize int,頁面大小,如每頁儲存20條記錄 pageindex int 當前頁碼 as set nocount on begin declare indextable table id int id...

SQL 分頁儲存過程

create procedure splitpage sql nvarchar 4000 不帶排序語句的sql語句 page int,頁碼 recsperpage int,每頁容納的記錄數 id varchar 255 需要排序的不重複的id號 sort varchar 255 排序欄位及規則 as...