August 04, 2011

SQL Server: Retreive all records between Two Rows of a Table without a Numeric Primary Key

Let us quickly see how to fetch all the records between two rows in a SQL Server table which does not have a numeric primary key.
We will use the Northwind database for our sample and this query has been tested on SQL Server 2005 and 2008.  The table Customer in the Northwind database has a primary key that is non-numeric. So in order to find the rows between position 10 and 20 (ordered by CustomerID), we will use a CTE (Common Table Expression) to do so. Here’s the query:
USE NORTHWIND
GO
DECLARE @Start as smallint = 10;
DECLARE @End as smallint = 20;

WITH CTE AS
(
SELECT ROW_NUMBER() OVER (ORDER BY CustomerID) AS cid,
CustomerID, CompanyName           
FROM Customers
)
SELECT cid as ID, CustomerID,  CompanyName   
FROM CTE
WHERE cid BETWEEN @Start AND @End

OUTPUT

image


About The Author

Suprotim Agarwal, ASP.NET Architecture MVP works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He has also written an EBook 51 Recipes using jQuery with ASP.NET Controls.

Follow him on twitter @suprotimagarwal

No comments: