1

本文的帮助和 SO 专家最近的回答下,我得到了以下内容,这将帮助我有效地翻阅一组记录。

我想我的最后几个问题是

  1. 看看我如何Total Number of Records在名为“Total”的 SQL CTE 末尾包含有效负载。你会这样做吗?
  2. 还有其他建议吗?更简洁或改进的潜在领域?Return Total Number of Pages

DECLARE @page_size INT = 5;
DECLARE @page_nbr INT = 4;
DECLARE @search NVARCHAR(MAX) = '';
DECLARE @sort_order INT = 2;

WITH AllProducts
AS
(
SELECT *, 
CASE @sort_order
    WHEN 1 THEN ROW_NUMBER() OVER ( ORDER BY ProductID )
    WHEN 2 THEN ROW_NUMBER() OVER ( ORDER BY ProductName )
END AS 'Seq'    
FROM Products
),
Filtered
AS
(
SELECT * FROM AllProducts
WHERE ProductName like '%'+@search+'%'
OR
@search is null
)
SELECT (select COUNT(*) from Filtered) as 'Total', * FROM Filtered
WHERE seq > (@page_nbr - 1) * @page_size
  AND seq <= @page_nbr * @page_size
4

1 回答 1

1

我认为您的查询有问题:它对记录进行编号(用于分页),然后应用过滤器。

例如,您可能请求记录的第 2 页,但同时seq可能会过滤掉所有具有相应值的记录。因此,在这种情况下,查询不会产生任何结果,尽管表中可能有大量记录。

为了解决这个问题,您可以在同一个 CTE 中进行过滤和记录编号,如下所示:

DECLARE @page_size INT = 5;
DECLARE @page_nbr INT = 4;
DECLARE @search NVARCHAR(MAX) = '';
DECLARE @sort_order INT = 2;

WITH Filtered AS (
    SELECT *, 
        CASE @sort_order
            WHEN 1 THEN ROW_NUMBER() OVER ( ORDER BY ProductID )
            WHEN 2 THEN ROW_NUMBER() OVER ( ORDER BY ProductName )
        END AS 'Seq'
    FROM AllProducts
    WHERE ProductName like '%'+@search+'%' OR @search is null
)
SELECT (select COUNT(*) from Filtered) as 'Total', * FROM Filtered
WHERE seq > (@page_nbr - 1) * @page_size
  AND seq <= @page_nbr * @page_size
于 2012-11-03T18:18:00.580 回答