Return total records from SQL Server when using ROW_NUMBER(使用 ROW_NUMBER 时从 SQL Server 返回总记录)
问题描述
我想返回数据库中的记录总数,以便设置分页.SQL Server 2008中使用以下分页方式时,如何返回DB中的记录总数?
I would like to return the total number of records in the database so I can set up pagination. How do I return the total number of records in the DB when using the following paging method in SQL Server 2008?
ALTER PROCEDURE [dbo].[Nop_LoadAllOptimized]
(
@PageSize int = 20,
@PageNumber int = 1,
@WarehouseCombinationID int = 1,
@CategoryId int = 58,
@OrderBy int = 0,
@TotalRecords int = null OUTPUT
)
AS
BEGIN
WITH Paging AS (
SELECT rn = (ROW_NUMBER() OVER (
ORDER BY
CASE WHEN @OrderBy = 0 AND @CategoryID IS NOT NULL AND @CategoryID > 0
THEN pcm.DisplayOrder END ASC,
CASE WHEN @OrderBy = 0
THEN p.[Name] END ASC,
CASE WHEN @OrderBy = 5
THEN p.[Name] END ASC,
CASE WHEN @OrderBy = 10
THEN wpv.Price END ASC,
CASE WHEN @OrderBy = 15
THEN wpv.Price END DESC,
CASE WHEN @OrderBy = 20
THEN wpv.Price END DESC,
CASE WHEN @OrderBy = 25
THEN wpv.UnitPrice END ASC
)), p.*, pcm.DisplayOrder, wpv.Price, wpv.UnitPrice FROM Nop_Product p
INNER JOIN Nop_Product_Category_Mapping pcm ON p.ProductID=pcm.ProductID
INNER JOIN Nop_ProductVariant pv ON p.ProductID = pv.ProductID
INNER JOIN Nop_ProductVariant_Warehouse_Mapping wpv ON pv.ProductVariantID = wpv.ProductVariantID
WHERE pcm.CategoryID = @CategoryId AND (wpv.Published = 1 AND pv.Published = 1 AND p.Published = 1 AND p.Deleted = 0)
AND wpv.WarehouseID IN (select WarehouseID from Nop_WarehouseCombination where UserWarehouseCombinationID = @WarehouseCombinationID)
)
SELECT TOP (@PageSize) * FROM Paging PG
WHERE PG.rn > (@PageNumber * @PageSize) - @PageSize
SET @TotalRecords = @@ROWCOUNT
END
推荐答案
我通常这样做 - 从性能的角度来看,我从来没有真正检查过它是否非常有效:
I typically do it this way - never really checked whether it's very efficient from a performance point of view:
WITH YourCTE AS
(
SELECT
(list of columns),
ROW_NUMBER() OVER (ORDER BY ......) AS 'RowNum'
FROM dbo.YourBaseTable
)
SELECT
*,
(SELECT MAX(RowNum) FROM YourCTE) AS 'TotalRows'
FROM
YourCTE
WHERE
RowNum BETWEEN 101 AND 150
基本上,RowNum
值的值为 1 到总行数(如果 CTE 中没有 PARTITION BY
),因此选择 MAX(RowNum)
,得到总行数.
Basically, the RowNum
value will have values 1 through the total of rows (if you don't have a PARTITION BY
in your CTE) and thus selecting MAX(RowNum)
, you get the total number of rows.
这篇关于使用 ROW_NUMBER 时从 SQL Server 返回总记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 ROW_NUMBER 时从 SQL Server 返回总记录
基础教程推荐
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01