sqlsql-serversql-server-2000auto-incrementrow-number

MSSQL Select statement with incremental integer column... not from a table


I need, if possible, a t-sql query that, returning the values from an arbitrary table, also returns a incremental integer column with value = 1 for the first row, 2 for the second, and so on.

This column does not actually resides in any table, and must be strictly incremental, because the ORDER BY clause could sort the rows of the table and I want the incremental row in perfect shape always.

The solution must run on SQL Server 2000


Solution

  • For SQL 2005 and up

    SELECT ROW_NUMBER() OVER( ORDER BY SomeColumn ) AS 'rownumber',*
        FROM YourTable
    

    for 2000 you need to do something like this

    SELECT IDENTITY(INT, 1,1) AS Rank ,VALUE
    INTO #Ranks FROM YourTable WHERE 1=0
    
    INSERT INTO #Ranks
    SELECT SomeColumn  FROM YourTable
    ORDER BY SomeColumn 
    
    SELECT * FROM #Ranks
    Order By Ranks
    

    see also here Row Number