Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server how to update a column for a desired row number

Any idea how I can update a column but only for row number=1 to row number=10 for example?

like image 457
largo68 Avatar asked Jul 18 '11 07:07

largo68


People also ask

Can we use row number in UPDATE statement?

> Is it possible to use Row_Number() function in an UPDATE statement? Yes. > However, I'm getting this error: "Subquery returned more than 1 value.

How do you UPDATE a column based on a filter of another column?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.


1 Answers

This uses a derived table to isolate the 10 rows you want to update. Note, they both have an ORDER BY in them to determine the 10 rows

UPDATE
   T
SET
   SomeColumn = @newValue --or constant etc
FROM
   (
   SELECT
      *,
      ROW_NUMBER() OVER (ORDER BY something) AS rn
   FROM
      SomeTable
   WHERE
      ...
   ) T
WHERE
   rn <= 10
like image 52
gbn Avatar answered Nov 04 '22 01:11

gbn