在cte中返回总记录

时间:2012-11-03 16:48:09

标签: sql sql-server sql-server-2008 tsql

article here的帮助下以及SO专家最近的回答中,我得到了以下内容,这将有助于我有效地翻阅一组记录。

我认为我的最后几个问题是

  1. 了解我最后如何在有效负载中包含Total Number of Records SQL CTE称为“总计”。这是你怎么做的?
  2. 还有其他建议吗?更简洁或改进的潜在领域? Return Total Number of Pages

  3. 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
    

1 个答案:

答案 0 :(得分: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