Rownum in SQL Server
-
Posted on June 13, 2010 by Derek Dieter
-
2
Prior to SQL Server 2005, there was no inherent function to generate a rownumber within a row. There is a workaround however for SQL 2000. If you are on SQL 2005+, then you will utilize the following function:
Method 1
SELECT
RowNumber = ROW_NUMBER() OVER (ORDER BY c.CustomerID ASC)
,c.*
FROM SalesLT.Customer c
Method 2
There are two ways to do this in SQL 2000. The easiest way is to join the table on itself and count the number of rows that precede the primary key.
SELECT Rownum =
(
SELECT COUNT(1)
FROM SalesLT.Customer
WHERE CustomerID <= c.CustomerID
), *
FROM SalesLT.Customer c
ORDER BY CustomerID
Method 3
The other way for SQL 2000 is to use the IDENTITY function in order to generate a Rownum. The downside is that you must insert the results into a temp table, then select from the temp table in order to retrieve the rownum.
SELECT
RowNumber = IDENTITY(INT,1,1)
,c.LastName
,c.FirstName
INTO #Customer_RowID
FROM SalesLT.Customer c
ORDER BY c.LastName ASC
SELECT *
FROM #Customer_RowID
Also notice from this example that when we insert the results into the temp table, we are specifying the column names. This is because the identity function will not work if you include the primary key of the table, which is another downside.
- Comments (RSS)
- Trackback
- Permalink
Method 1 was quit easy and understandable helped me alot thanks for the post………





