Limiting rows in CTE with pagination? SQL 2008R2

  • I have been asked to look at tuning a improving an SP query that uses an CTE and rownumber on a table that holds 30m records. It looks like it is having to work on the full result set of 30m rows to do the numbering so it is taking minutes to run. I want to limit it the query within the CTE to look at only the top 1000 rows to speed up performance but am struggling with the syntax.

    The output is used in a webscreen that requires pagination control so the RowNumber and TotalRowCount are required for 'Page x of y' control.

    Every change I attempt either breaks the query or messes up the pagination. Is there a way I can limit the CTE to the top x records? Code example below. I'd really appreciate some assistance.

    Many thanks

    Steve

    Declare @sortcriteria nvarchar (50) = 'Date DESC',

    @filterCriteria nvarchar (50) = '12345'

    ;WITH CTE AS (

    SELECT

    -- get

    ROW_NUMBER() OVER(

    ORDER BY

    CASE

    WHEN @sortCriteria = 'Date ASC' then T.AuditDate

    WHEN @sortCriteria = 'UserName ASC' then T.UserName

    END ASC,

    CASE

    WHEN @sortCriteria = 'Date DESC' then T.AuditDate

    WHEN @sortCriteria = 'UserName ASC' then T.UserName

    END DESC) AS SortingRowNumber,

    COUNT(*) OVER(PARTITION BY NULL) AS TotalRowCount,

    Col1,

    Col2

    FROM Table1 T

    INNER JOIN Tables ON ....

    WHERE

    T.Id = @FilterCritera

    )

    SELECT

    SortingRowNumber,

    TotalRowCount,

    Col1,

    Col2

    FROM

    CTE

  • Ah sorry - forum newbe - please move to the SQL2008 - T SQL board :unsure:

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply