SQLUSA
BI TRIO 2008
FREE TRIAL
CLICK HERE TO ORDER

SQL Server 2008 Best Practices
SQL Server 2005 Best Practices

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

*/

 

The World Leader in SQL Server 2008 Training
The future is just a CLICK away. Your future!
 
SQLUSA.com Home Page

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

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.