Pergunta

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.

Foi útil?

Solução

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.

Outras dicas

If you are only updating a few thousand rows, you could try something like this:

select 'UPDATE MyTable SET ID = ' + CAST(RowID as varchar) + ' WHERE ID = ' + CAST(ID as varchar)
From (
select MyTable, ROW_NUMBER() OVER (ORDER BY SortColumn) RowID from RaceEntry 
where SomeClause and SomeOtherClause
) tbl

Copy and paste the query results into the query editor and run. It's a bit sluggish and yukky bit it works.

Simple workaround would be to create a temp table that looks like

CREATE TABLE #temp (id int, rank int)

Where id is the same type as primary key in you main table.

Just use SELECT INTO to first fill temp table and then update from temp table…

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top