SQL 分頁儲存過程

2021-07-12 07:23:37 字數 1907 閱讀 7957

--author: longxi zhu

--date: 2016-06-02

--description: get paged list

create procedure usp_cosmos_getpagedjobs

@tablename varchar(50),

@fields varchar(max),

@strwhere varchar(max),--條件

@orderfield varchar(50),

@pageindex int=1,--頁索引

@pagesize int,--每頁顯示條數

@pagecount int output,--總頁數

@totalcount int output--總條數

asbegin

set nocount on;

declare @sql nvarchar(max);

if(isnull(@strwhere,'')='')

begin

set @sql='select @totalcount=count(*)from ' +@tablename;

endelse

begin

set @sql='select @totalcount=count(*) from '+@tablename+' where '+@strwhere

endexec sp_executesql @sql,n'@totalcount int output',@totalcount output;--計算總條數

--計算總頁數

select @pagecount=ceiling((@totalcount+0.0)/@pagesize);

if(isnull(@strwhere,'')='')

begin

set @sql='select * from (select row_number() over(order by '+@orderfield+') as rowid,'+@fields+' from '+@tablename;

endelse

begin

set @sql='select * from (select row_number() over(order by '+@orderfield+') as rowid,'+@fields+' from '+@tablename+' where '+@strwhere;

end--處理頁超出範圍情況

if(@pageindex<=0)

begin

set @pageindex=1;

endif(@pageindex>@pagecount)

begin

set @pageindex=@pagecount;

end--處理開始點和結束點

declare @beginindex int,@endindex int

set @beginindex=(@pageindex-1)*@pagesize+1

set @endindex=@pageindex*@pagesize

--繼續組織sql語句

set @sql=@sql+') as a'+' where rowid between '+convert(varchar,@beginindex) +' and '+convert(varchar,@endindex);

exec (@sql);

set nocount off;

enddeclare @pagecount1 int, @totalcount1 int

exec usp_cosmos_getpagedjobs 'jobs','*','alias like ''%v-lozhu%''','id',3,3,@pagecount1 output,@totalcount1 output

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...