sql分頁儲存過程

2022-08-03 18:36:14 字數 2366 閱讀 4821

alter procedure [dbo].[p_splitpagesquery]

@tablesname nvarchar(max),--表名或檢視名(只能傳單一表名)

@pk nvarchar(max)='',--主鍵(可以為空!)

@strsort nvarchar(max)='',--排序字段(按照這個欄位對查詢結果進行排序),不能為空 @sorttype int =0,--排序方式,預設為0(公升序),1為降序

@strwhere nvarchar(max)='',--查詢條件(即sql語句中的where後面部分)

@fields nvarchar(max)='*',--讀取字段(呈現出來的字段)

@pagecurrent int =1,--當前頁碼,預設為1

@pagesize int =10,--頁面大小,預設為10

@pagecount int output,--總頁數(按照頁面大小一共分了多少頁)

@recordcount int output--查詢結果的總條數 as /*     返回值說明:查詢結果(表) */

declare @sqlstr nvarchar(4000)

if @strwhere is not null and @strwhere != ''   

begin     

set @strwhere = ' where ' + @strwhere + ' '   

endelse   

begin      

set @strwhere = ''   

endbegin    if @strsort = ''      

if @pk  is not null and @pk!=''                

set @strsort = @pk   

if @pagecurrent < 1      

set @pagecurrent = 1     

if @sorttype = 1 and @strsort!=''           

set @strsort = @strsort + ' desc '   

if @sorttype = 0 and @strsort!=''           

set @strsort = @strsort + ' asc '

if @pagecurrent = 1 --第一頁提高效能       

begin           

set @sqlstr = 'select top ' + str(@pagesize) +' '+@fields+ ' from ' + @tablesname +               ' as tb ' + @strwhere  

if @strsort!=''                            

set @sqlstr = @sqlstr + ' order by '+ @strsort       

end   

else   

begin      

declare @startpos nvarchar(50)         

declare @endpos nvarchar(50)         

set @startpos = convert(nvarchar(50),(@pagecurrent - 1) * @pagesize + 1)         

set @endpos = convert(nvarchar(50),@pagecurrent * @pagesize)         

set @sqlstr =  ' select '+@fields+ '   from (select row_number() over(order by '+@strsort+') as rownum , tb.* '+'   from '+@tablesname+' as tb '+@strwhere+') as d   where rownum between '+@startpos+' and ' +@endpos                 

if @strsort!=''                            

set @sqlstr = @sqlstr + ' order by '+ @strsort      

endend

print @sqlstr exec(@sqlstr)

declare @sqlcount nvarchar(4000)

set @sqlcount = 'select @recordcount=count(*),@pagecount=ceiling((count(*)+0.0)/'   + cast(@pagesize as varchar)+') from ' + @tablesname + @strwhere

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