Better way for Getting Total Count along with Paging in SQL Server 2012(在 SQL Server 2012 中获取总计数和分页的更好方法)
问题描述
我需要获取记录总数和分页.目前我正在按照下面列出的 SQL Server 2012 进行操作.这需要一个单独的查询来获取计数.SQL Server 2012 有什么改进的方法吗?
I have requirement to get the total count of records along with paging. At present I am doing it as listed below in SQL Server 2012. This needs a separate query for getting count. Is there any improved way in SQL Server 2012?
ALTER PROCEDURE dbo.tpGetPageRecords
(
@OffSetRowNo INT,
@FetchRowNo INT,
@TotalCount INT OUT
)
AS
SELECT CSTNO, CSTABBR
FROM DBATABC
WHERE CSTABBR LIKE 'A%'
ORDER BY CSTNO
OFFSET ( @OffSetRowNo-1 ) * @FetchRowNo ROWS
FETCH NEXT @FetchRowNo ROWS ONLY
SET @TotalCount =
(SELECT COUNT(*)
FROM DBATABC
WHERE CSTABBR LIKE 'A%')
GO
推荐答案
如果我们被允许更改合同,您可以:
If we're allowed to change the contract, you can have:
SELECT CSTNO, CSTABBR,COUNT(*) OVER () as TotalCount
FROM DBATABC
WHERE CSTABBR LIKE 'A%'
ORDER BY CSTNO
OFFSET ( @OffSetRowNo-1 ) * @FetchRowNo ROWS
FETCH NEXT @FetchRowNo ROWS ONLY
现在总数将作为结果集中的单独列提供.不幸的是,无法在同一语句中将此值分配给变量,因此我们不能再将其作为 OUT
参数提供.
And now the total will be available as a separate column in the result set. Unfortunately, there's no way to assign this value to a variable in this same statement, so we can no longer provide it as an OUT
parameter.
这使用了 OVER
子句(自 2005 年可用)允许在整个(无限)结果集上计算聚合,而无需 GROUP
ing.
This uses the OVER
clause (available since 2005) to allow an aggregate to be computed over the entire (unlimited) result set and without requiring GROUP
ing.
这篇关于在 SQL Server 2012 中获取总计数和分页的更好方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 SQL Server 2012 中获取总计数和分页的更好方法
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 在SQL中,如何为每个组选择前2行 2021-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01
- SQL 临时表问题 2022-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01