Getting total row count from OFFSET / FETCH NEXT

前端 未结 3 799
花落未央
花落未央 2020-12-02 05:40

So, I\'ve got a function that returns a number of records that I want to implement paging for on my website. It was suggested to me that I use the Offset/Fetch Next in SQL

3条回答
  •  独厮守ぢ
    2020-12-02 06:34

    You can use COUNT(*) OVER() ... here is a quick example using sys.all_objects:

    DECLARE 
      @PageSize INT = 10, 
      @PageNum  INT = 1;
    
    SELECT 
      name, object_id, 
      overall_count = COUNT(*) OVER()
    FROM sys.all_objects
    ORDER BY name
      OFFSET (@PageNum-1)*@PageSize ROWS
      FETCH NEXT @PageSize ROWS ONLY;
    

    However, this should be reserved for small data sets; on larger sets, the performance can be abysmal. See this Paul White article for better alternatives, including maintaining indexed views (which only works if the result is unfiltered or you know WHERE clauses in advance) and using ROW_NUMBER() tricks.

提交回复
热议问题