sql 幾種分頁查詢的儲存過程

2021-06-02 20:08:59 字數 3090 閱讀 7079

今天好好的找了下分頁的儲存過程,並測試了下,在此記下:

第一種:

alter proc [dbo].[select_colname]

( @pagesize int,

@currentpage int

)as

select top (@pagesize) colname from dbo.tablename

where colname not in (

select top(@pagesize*(@currentpage-1)) colname from dbo.tablename)

return

執行的語句:

declare @return_value int

exec @return_value = [dbo].[select_colname]

@pagesize = 50000,

@currentpage = 100

select 'return value' = @return_value

go

第二種:
alter proc [dbo].[select_colname_two]

( @page int ,

@pagesize int

)as

select colname from

( select colname,row_number() over(order by colname) as sql_rownumber from tablename)

as normren where sql_rownumber between @pagesize*(@page-1) and @pagesize*@page

執行語句:

declare @return_value int

exec @return_value = [dbo].[select_email_two]

@page = 100,

@pagesize = 50000

select 'return value' = @return_value

go

第三種:

alter procedure [dbo].[getrecordfrompage]  

( @tblname varchar(255), -- 表名

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

@pagesize int , -- 頁尺寸

@pageindex int , -- 頁碼

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

@strwhere varchar(2000) = ''

) -- 查詢條件 (注意: 不要加 where)

as

declare @strsql varchar(6000) -- 主語句

declare @strtmp varchar(1000) -- 臨時變數

declare @strorder varchar(500) -- 排序型別

if @ordertype != 0

begin

set @strtmp = '<(select min'

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

end

else

begin

set @strtmp = '>(select max'

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

end

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

+ @tblname + '] where [' + @fldname + ']' + @strtmp + '(['

+ @fldname + ']) from (select top ' + str((@pageindex-1)*@pagesize) + ' ['

+ @fldname + '] from [' + @tblname + ']' + @strorder + ') as tbltmp)'

+ @strorder

if @strwhere != ''

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

+ @tblname + '] where [' + @fldname + ']' + @strtmp + '(['

+ @fldname + ']) from (select top ' + str((@pageindex-1)*@pagesize) + ' ['

+ @fldname + '] from [' + @tblname + '] where ' + @strwhere + ' '

+ @strorder + ') as tbltmp) and ' + @strwhere + ' ' + @strorder

if @pageindex = 1

begin

set @strtmp = ''

if @strwhere != ''

set @strtmp = ' where (' + @strwhere + ')'

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

+ @tblname + ']' + @strtmp + ' ' + @strorder

end

exec (@strsql)

sql 儲存過程分頁查詢

第一次遇到儲存過程分頁弄了挺長時間 主要用到了row number over 方法,此方法自動生成乙個num 列,更具over中的列排序,從一開始公升序 drop proc getpageshowoptionnumpnum gocreate proc aa currpagenum int,當前頁數 ...

SQL查詢通用儲存過程(可分頁)

以前參考過網上朋友 是誰忘了,知道的說一聲 寫的,但感覺有點不適合我的要求。修改大部分後如下所示。getrecordpagetotal為分頁時取得頁總數。當然可以寫在getrecordbypage裡,但個人認為那樣的話,在只取頁總數的情況下也要使用getrecordbypage,查詢效率不太好,就分...

sql 儲存過程分頁

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