1

我有一个正在运行的存储过程,我正在尝试使用分页但也返回整个产品计数。它正在“工作”,但问题是当我取出 totalCount CTE 并将其从最终的 SELECT 中删除时,我的 sproc 运行时间约为 50 毫秒。当我把它放在那里时,我的查询需要 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
4

1 回答 1

2

您可以使用以下方法来检索计数,而无需执行子选择。

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

SQLFIDDLE

于 2013-11-02T22:39:07.177 回答