SQL Server利用RowNumber()內置函數與Over關鍵字實現通用分頁存儲過程,支持單表或多表結查集分頁,存儲過程如下:
/******************/--Author:夢在旅途(www.Zuowenjun.cn)--CreateDate:2015-06-02--Function:分頁獲取數據/******************/create PRocedure [dbo].[sp_DataPaging](@selectsqlnvarchar(200),--查詢字段SQL,不含select,支持靈活寫法,如:col1,col3,isnull(col4,'') as col4@fromsqlnvarchar(500),--查詢表及條件SQL,不含from,若包含條件請加上where,如:table where col1='test'@orderbysql nvarchar(100),--查詢排序SQL,不含order by,如:id order by desc@pagesizeint=20,--每頁顯示記錄數@pagenoint=1,--當前查詢頁碼,從1開始@returnrecordcount bit=1 --是否需要返回總記錄數,若設為1,則返回兩個結果表)asbegindeclare @sqlcount nvarchar(500),@sqlstring nvarchar(max)set @sqlstring=N'from (select row_number() over (order by ' + @orderbysql + N') as rowId,' + @selectsql + N' from '+ @fromsql +N') as t'if(@returnrecordcount=1)beginset @sqlcount=N'select count(rowId) as resultcount ' + @sqlstringexec(@sqlcount)endset @sqlstring=N'select * ' + @sqlstring + ' where rowId between ' + convert(nvarchar(50),(@pageno-1)*@pagesize+1)+' and '+convert(nvarchar(50),@pageno*@pagesize)exec(@sqlstring)end
用法如下:
--單表查詢exec [dbo].[sp_DataPaging] '*','AssetDetail','assetsingleno',10,1--多表查詢exec [dbo].[sp_DataPaging] 'a.*','Inventory a left join AssetDetail b on a.StoreNo=b.StoreNo and a.CompanyID=b.CompanyIDinner join Asset c on b.AssetID=c.ID and b.CompanyID=c.CompanyID','a.id',20,3,1
結果顯示如下(如上多表查詢):
新聞熱點
疑難解答