sql通用儲存過程分頁
阿新 • • 發佈:2022-03-08
SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO -- ============================================= -- Author: 瀟瀟與偕 -- Create date: -- Description: 分頁儲存過程 -- ============================================= create PROCEDURE p_Common_DataPager_New @sqlstr nvarchar(max), --SQL statement @currentpageint, --page # @pagesize int, --size of page @rowcount int output, @pagecount int output AS BEGIN set nocount on declare @countSql nvarchar(max) declare @dataSql nvarchar(max) declare @dbwhitespaceIndex int=0 declare @orderbyStr nvarchar(max) --處理掉多餘空格set @dbwhitespaceIndex=CHARINDEX(' ',@sqlStr) while @dbwhitespaceIndex>0 begin set @sqlStr=REPLACE(@sqlStr,' ',' ') set @dbwhitespaceIndex=CHARINDEX(' ',@sqlStr) end print ('@orderbyStr:'+@orderbyStr) --組裝無排序欄位的查詢sql if CHARINDEX('ORDER BY',@sqlStr)=0 begin --擷取排序欄位 set @orderbyStr='' set @dataSql='declare @tempTable table ( TemplTableSortId int ); select top '+CONVERT(nvarchar(10),@pagesize)+' dt.* from ( select ROW_NUMBER() over(order by t.TemplTableSortId) sortid,s.* from ('+@sqlstr+') s left join @tempTable t on 0=1) dt where dt.sortid> '+convert(nvarchar(10),(@currentpage-1)*@pagesize) end --組裝有排序欄位的sql else begin select @orderbyStr= SUBSTRING(@sqlStr,CHARINDEX('ORDER BY',@sqlStr),LEN(@sqlStr)) set @dataSql='select top '+CONVERT(nvarchar(10),@pagesize)+' dt.* from ( select ROW_NUMBER() over('+@orderbyStr+') sortid,'+ SUBSTRING(@sqlStr,CHARINDEX('SELECT',@sqlStr)+6,LEN(@sqlStr)-len(@orderbyStr)-6)+') dt where dt.sortid>'+convert(nvarchar(10),(@currentpage-1)*@pagesize) end --查詢總行數 set @countSql='select @totalcount=count(*) from ('+ SUBSTRING(@sqlStr,0,LEN(@sqlStr)-len(@orderbyStr))+') t' exec sp_executesql @countSql, N'@totalcount int out',@rowcount out --計算總頁數 set @pagecount=@rowcount/@pagesize if @rowcount%@pagesize>0 begin set @pagecount+=1 end exec(@dataSql) set nocount off END GO