Sql2005中分頁儲存過程

2021-05-21 22:13:57 字數 2512 閱讀 5593

set ansi_nulls on

goset ansi_nulls on

set quoted_identifier on

goalter procedure pagetest

@tblname      varchar(255),       -- 表名

@fldname      varchar(255),       -- 主鍵欄位名

@pagesize     int = 10,           -- 頁尺寸

@pageindex    int = 1,            -- 頁碼

@ordertype    bit = 1,            -- 設定排序型別, 非 0 值則降序

@strwhere     varchar(1000) = '', -- 查詢條件 (注意: 不要加 where)

@pagecount int = 1 output,    -- 總頁數

@recordcount int = 1 output       --總條數 

asdeclare @strsql   nvarchar(4000)       -- 主語句

declare @strtmp   nvarchar(4000)       -- 臨時變數

declare @strorder nvarchar(400)        -- 排序型別

declare @strcount nvarchar(4000)       -- 統計條數

declare @pagesizestart int

declare @pagesizeend int

if @ordertype != 0

begin

set @strorder =' order by '+@fldname+' desc '

endelse

begin

set  @strorder =' order by '+@fldname+' asc '

end

if @strwhere !=''

begin

if str(@pageindex) = 1

set @strsql = 'select top '+str(@pagesize)+' * from '+@tblname+' where '+@strwhere

+''+@strorder

else

begin

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

set @pagesizeend = @pageindex*@pagesize

set @strsql = 'select * from (select *, row_number() over('+@strorder+') as row from

'+@tblname+' where '+@strwhere+'  ) as a where row between '+@pagesizestart+' and '+@pagesizeend

endend

else

begin

if str(@pageindex) = 1

begin

set @strsql = 'select top '+str(@pagesize)+' * from '+@tblname+''+@strorder

endelse

begin

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

set @pagesizeend = @pageindex*@pagesize

set @strsql = 'select * from (select *, row_number() over('+@strorder+') as row from

'+@tblname+') as a where row between '+str(@pagesizestart)+' and '+str(@pagesizeend)+''

endend  

------取得查詢結果總數量-----

if @strwhere != ''

set @strcount = 'select @recordcount = count(*) from [' + @tblname + ']'+' where ' + @strwhere

else

set @strcount = 'select @recordcount = count(*) from [' + @tblname + ']'

exec sp_executesql @strcount,n'@recordcount int out',@recordcount out

--取得分頁總數

if @recordcount <= @pagesize 

set @pagecount = 1

else

set @pagecount = (@recordcount-1)/@pagesize +1

print(@strsql)

exec(@strsql)

SQL 2005 儲存過程分頁

create procedure dbo p pagetest sql nvarchar max sql語句不包括排序 curpage int,當前頁 pagerows int,頁面尺寸 order nvarchar 20 排序字段 ordertype nvarchar 10 排序型別倒序desc或...

SQL2005中利用儲存過程分頁

進行top查詢時 引數需要帶上 declare page int,pagesize int set page 2 select top page from usertb 分頁 select top 2 from usertb where userid not in select top 2 user...

SQL 2005 多表分頁儲存過程

region 返回所有職位物件 帶分頁 region 返回所有職位物件帶分頁 當前頁 每頁顯示數 返回 頁數 返回總項數 物件集合 public static listgetallmodel int curpage,int size,ref int pagesize,ref int totalsiz...