您的位置:首页 > 数据库

数据量大的SQL分页查询优化

2014-04-19 22:02 260 查看
我们平常写分页sql,一般都会分两次查询,一次查询结果,一次查询总行数。下面这条sql做了一些优化,只需要查询一次。
代码如下:

declare @nGotoPage int,@nPageSize int;
set @nGotoPage = 1;
set @nPageSize  = 100000;
with T_Data(RowID,ID,CID,DisplayName,WriteDate,Body)
as
(
select Row_Number() over (order by ID) as RowID,
ID,CID,DisplayName,WriteDate,Body
from Test
where CID=1

),T_DataCount(nRecordCount)
as
(
select count(*) from T_Data
)
select _RecordCount=t2.nRecordCount,_PageCount=Ceiling(t2.nRecordCount * 1.0 / @nPageSize),
t1.* from T_Data as T1, T_DataCount as t2
where  RowID > ((@nGotoPage - 1) * @nPageSize) and RowID <= (@nGotoPage * @nPageSize);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: