CTE分页,与Count

时间:2013-11-02 00:06:06

标签: sql-server tsql sql-server-2005 pagination common-table-expression

我有一个正在运行的程序,我正在尝试使用分页,但也会返回整个产品计数。这是“工作”但问题是,当我拿出totalCount CTE并从最终的SELECT中删除它时,我的sproc运行在~50ms。当我将它保留在那里时,我的查询需要7-8秒。如果我抓住所有记录但这个想法是抓住我需要的页面但是我需要返回总记录,这是一个大问题。有没有更有效的方法来做到这一点?

/ **主要搜索块** /

WITH search_results AS
(

SELECT DISTINCT     
    ROW_NUMBER() OVER (ORDER BY @sortExpression) as rowNumber,
            products.pid,
            brands.bid,
            brands.brand_name,
            products.model,
            products.name,
            products.searchedprice
            products.status

FROM products WITH (NOLOCK)
            JOIN brands WITH (NOLOCK) ON products.bid=brands.bid

WHERE   
    (
           CONTAINS(products.*,@inflectionSearchText)
           OR
           CONTAINS(brands.Brand_Name,@inflectionSearchText)
    )
    AND
      products.productstatus=1
    AND 
      brands.brandstatus=1
    AND
      products.searchedprice BETWEEN @fromprice TO @toprice

),
totalCount AS 
(SELECT COUNT(*) Total FROM search_results)

SELECT * 
FROM search_results, totalCount
WHERE 
     rowNumber BETWEEN ((@pageNumber-1)*@pageSize)+1 
         AND ((@pageNumber-1)*@pageSize)+@pageSize

ORDER BY products.model

1 个答案:

答案 0 :(得分:2)

您可以使用以下方法检索计数而不执行子选择。

SELECT some_field, COUNT(*) OVER() AS total
FROM some_table

SQLFIDDLE