How to add row number column in SQL Server 2012

Michael Carper picture Michael Carper · Aug 25, 2013 · Viewed 42.7k times · Source

I'm trying to add a new column to an existing table, where the value is the row number/rank. I need a way to generate the row number/rank value, and I also need to limit the rows affected--in this case, the presence of a substring within a string.

Right now I have:

UPDATE table
SET row_id=ROW_NUMBER() OVER (ORDER BY col1 desc) FROM table
WHERE CHARINDEX('2009',col2) > 0

And I get this error:

Windowed functions can only appear in the SELECT or ORDER BY clauses.

(Same error for RANK())

Is there any way to create/update a column with the ROW_NUMBER() function? FYI, this is meant to replace an incorrect, already-existing "rank" column.

Answer

Ian Preston picture Ian Preston · Aug 26, 2013

You can do this with a CTE, something like:

with cte as
(
  select *
    , new_row_id=ROW_NUMBER() OVER (ORDER BY col1 desc)
  from MyTable
  where charindex('2009',col2) > 0
)
update cte
set row_id = new_row_id

SQL Fiddle with demo.