Sql分頁儲存過程

2021-08-30 19:03:37 字數 2879 閱讀 1375

alter procedure [dbo].[sp_common_select] 

@tablename nvarchar(200), --表名

@selectlist nvarchar(500), --欲選擇字段列表

@searchcondition nvarchar(2000), --查詢條件

@orderexpression nvarchar(500), --排序表示式

@pageindex int = 0, --頁號,從0開始

@pagesize int = 10, --頁大小

@totalcount int output, --記錄總數

@totalpages int output --頁面總數

as begin

--關閉返回計數

set nocount on

--設定where條件

set @searchcondition = isnull(@searchcondition,'')

set @searchcondition = ltrim(rtrim(@searchcondition))

if ltrim(rtrim(@searchcondition)) <> ''

begin

set @searchcondition = n' where ' + @searchcondition

end--獲得記錄總數

declare @sql nvarchar(2000)

set @sql=n'select @totalcount=count(*)'

+n' from '+@tablename

+' '+@searchcondition

exec sp_executesql @sql,n'@totalcount int output',@totalcount output

-- set @totalcount = 10

if @totalcount % @pagesize = 0

begin

set @totalpages = @totalcount / @pagesize

end

else

begin

set @totalpages = @totalcount / @pagesize + 1

end

--設定選擇字段

if @selectlist is null or ltrim(rtrim(@selectlist)) = ''

begin

set @selectlist = '*'

end--設定oreder by 條件

set @orderexpression = ltrim(rtrim(@orderexpression))

set @orderexpression = isnull(@orderexpression,'')

if @orderexpression <> ''

begin

set @orderexpression = 'order by ' + @orderexpression

end--設定分頁數

if @pageindex is null or @pageindex < 0

begin

set @pageindex = 0

end

set @pageindex = @pageindex + 1

if @pagesize is null or @pagesize < 1

begin

set @pagesize = 5

end--構造查詢語句

declare @sqlquery nvarchar(2000)

--set @sqlquery='select ' + @selectlist + ',rownumber

--from

-- (select ' + @selectlist + ',row_number() over( '+ @orderexpression +') as rownumber

-- from '+ @tablename +' '+ @searchcondition +') as rownumbertablesource

--where rownumber between ' + cast(((@pageindex - 1)* @pagesize+1) as nvarchar)

--+ ' and ' +

--cast((@pageindex * @pagesize) as nvarchar)

--edit by xlli at 20100109 適應多表關聯查詢

set @sqlquery='select *

from

(select ' + @selectlist + ',row_number() over( '+ @orderexpression +') as rownumber

from '+ @tablename +' '+ @searchcondition +') as rownumbertablesource

where rownumber between ' + cast(((@pageindex - 1)* @pagesize+1) as nvarchar)

+ ' and ' +

cast((@pageindex * @pagesize) as nvarchar)

--執行查詢

execute sp_executesql @sqlquery

--開啟返回計數

set nocount off

end

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