Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Limiting rows in CTE with pagination? SQL 2008R2 Expand / Collapse
Author
Message
Posted Wednesday, September 25, 2013 4:29 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, September 25, 2013 4:29 AM
Points: 2, Visits: 2
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
Post #1498240
Posted Wednesday, September 25, 2013 4:31 AM
Forum Newbie

Forum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum NewbieForum Newbie

Group: General Forum Members
Last Login: Wednesday, September 25, 2013 4:29 AM
Points: 2, Visits: 2
Ah sorry - forum newbe - please move to the SQL2008 - T SQL board
Post #1498243
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse