SQLUSA.com
SQL SERVER 2008 GRAND SLAM
FREE TRIAL  CLICK HERE TO ORDER  SEARCH
SQL JOBS SQL Server Training Scripts JOB BANK
  SQL Server 2008 Training Scripts  
  SQL Server 2005 Training Scripts  
News SQL Server Articles SQL Format

How to filter result set by the ROW_NUMBER function?

Execute the following SQL Server Transact-SQL script in SSMS Query Editor to filter the result set of a CTE by applying ROW_NUMBER():

USE AdventureWorks

GO

-- SQL Server common table expression - CTE - SQL Server row_number

-- SQL over order by - SQL Server row numbering - row id

DECLARE  @BeginRow INT,

         @EndRow   INT

SET @BeginRow = 200

SET @EndRow = 280;

 

WITH ctePersonContact

     AS (SELECT FirstName,

                LastName,

                Phone,

                EmailAddress,

                RowNumber = ROW_NUMBER()

                              OVER(ORDER BY FirstName, LastName)

         FROM   Person.Contact)

SELECT   [Name] = FirstName + ' ' + LastName,

         Phone,

         EmailAddress,

         RowNumber

FROM     ctePersonContact

WHERE    RowNumber >= @BeginRow

         AND RowNumber <= @EndRow

ORDER BY [Name]

 

GO

/* Partial results

 

Name                    Phone                   EmailAddress                  RowNumber

Abby Fernandez          134-555-0119            abby13@adventure-works.com    248

Abby Garcia             1 (11) 500 555-0154     abby12@adventure-works.com    249

Abby Garcia             NULL                    Aabby12@adventure-works.com   250

Abby Garcia             1 (11) 500 555-0154     abby12@adventure-works.com    251

Abby Garcia             NULL                    Aabby12@adventure-works.com   252

Abby Gonzalez           NULL                    Aabby16@adventure-works.com   253

*/

 

Order SQL 2008 GRAND SLAM Today!
SQLUSA.com Home Page
SQL Server Training at www.sqlusa.com.
SQL Server 2008 Video Training at www.sqlusa.com.
SQL Server 2005 Training Videos at www.sqlusa.com.
Microsoft SQL Server 2000 Training Videos at www.sqlusa.com.

FREE SQL & Business Intelligence / OLAP Short Videos on YOUTUBE.com

Microsoft Community Contributor 2011
Invest in Your SUCCESS!

Search SQLUSA FREE SQL Server Articles & FREE T-SQL Scripts


Copyright 2005-2011, SMI Corp. All Rights Reserved.

SQL Server 2012 is a program product of Microsoft Corporation.
SQL Server 2008 is a program product of Microsoft Corporation.
SQL Server 2005 is a program product of Microsoft Corporation.
SQL Server 2000 is a program product of Microsoft Corporation.