最近在做一个几百万条数据的分页查询,研究了各种方案,在本机上用项目的实际数据库做测试,测试过程 is very 痛苦,不堪回首ing。现在废话不多说,直接上结果,相信这也是大多数搜索答案的人最愿意看的方式。
以下是存储过程的代码:
create procedure [dbo].[P_GridViewPager](
@recordTotal int ouput, --输出记录总数
@viewName varchar(800), --表名
@fieldName varchar (800)=‘*’, --查询字段
@keyName varchar(200)=‘id‘, --索引字段
@pageSize int=20, --每页记录数
@pageNo int=1, --当前页
@orderString varchar(200), --排序条件
@whereString varchar(800)=‘1=1‘ --where条件
)
as
begin
declare @beginRow int
declare @endRow int
declare @tempLmit varchar(200)
declare @tempCount nvarchar(1000)
declare @tempMain varchar(1000)
set nocount on
set @beginRow=(@pageNo-1)*@pageSize+1
SET @endRow = @pageNo * @pageSize
SET @tempLimit = ‘rows BETWEEN ‘ + CAST(@beginRow AS VARCHAR) +‘ AND ‘+CAST(@endRow AS VARCHAR) --输出参数为总记录数
SET @tempCount = ‘SELECT @recordTotal = COUNT(*) FROM (SELECT ‘[email protected]+‘ FROM ‘[email protected]+‘ WHERE ‘[email protected]+‘) AS my_temp‘
EXECUTE sp_executesql @tempCount,N‘@recordTotal INT OUTPUT‘,@recordTotal OUTPUT --主查询返回结果集
SET @tempMain = ‘SELECT * FROM (SELECT ROW_NUMBER() OVER (order by ‘[email protected]+‘) AS rows ,‘[email protected]+‘ FROM ‘[email protected]+‘ WHERE ‘[email protected]+‘) AS main_temp WHERE ‘[email protected]
--PRINT @tempMain
EXECUTE (@tempMain)
--select datediff(ms,@timediff,getdate()) as 耗时
set nocount off END
GO