在处理大数据量的SQL分页查询时,传统的做法是进行两次数据库查询:一次用于获取分页数据,另一次用于计算总记录数。这种做法在数据量较大时会显著影响性能。为了提高效率,可以通过使用CTE(Common Table Expressions)来优化这一过程,实现单次查询即可完成数据和总数的获取。
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);
上述SQL语句首先定义了两个CTE:T_Data用于获取排序后的数据行,T_DataCount用于计算满足条件的总记录数。通过这两个CTE,最终的SELECT语句能够一次性返回所需的分页数据及总记录数,避免了重复查询带来的性能开销。