tags:

views:

170

answers:

2

SQL Server Question:

I have a table with appx. 1000 already existing rows, and 5 columns

How can I update the value at row Y in column ?

I don't have any keys or conditions for the where.

+6  A: 
WITH    q AS (
        SELECT  m.*, ROW_NUMBER() OVER (ORDER BY column) AS rn
        FROM    mytable m
        )
UPDATE  q
SET     mycol = 'newvalue'
WHERE   rn = @Y

Note that in SQL there is no concept of implicit row order.

There is no n'th row unless you define the ordering condition (column in example above).

In this table:

col1 col2
1    2
2    1

, the row (1, 2) is first when ordering by col1, and second when ordering by col2.

Quassnoi
*<nitpick>* As he does not have any conditions for the where clause I assume there are identical rows in the table. If that is true, running this update might update different rows when the update runs twice (and the moon and planets are misalligned). I am sure **you** know this and I know in practice it most likely will not happen but in theory it might. *</nitpick>*
Lieven
but then again, it is as good as its gonna get. +1
Lieven
`@Lieven`: this is only good as a first-time query :) After the `UPDATE` succeeds the `@op` gets a new condition: `mycol = 'newvalue'` and the next `UPDATE` should use it.
Quassnoi
@Quassnoi: Oh for heavens sake, admit you just came up with that one didn't you! :)
Lieven
`@Lieven`: just couldn't help it!
Quassnoi
A: 

First, you add a primary key, whether you already have a candidate key (possibly even a composite key) or choose to use a surrogate key. You can then use that as your criteria in your where clause.

Rowland Shaw