views:

373

answers:

2

I need to update the first N rows in a table meeting a condition.

I know I can do an Update Top N... but the problem is that N is in a @variable.

UPDATE TOP @N SET ... doesn't work.

Is there a way to do this that I am just missing?

No specific table definitions here because it doesn't matter what the columns are.. If I can do it for a one column table I can do it for my table.

+8  A: 

You need to use parens after TOP clause when you want to use a variable:

UPDATE TOP(@N) ...
Mehrdad Afshari
Cool trick! Thanks for teaching it to me. Interestingly, this very syntax does not work with the 'SELECT TOP n' construct. I can why that would happen, although it is somewhat of an odd asymmetry in TSQL.
mjv
`SELECT TOP n` works only if `n` is a constant, not a variable. It worked like that before 2005. `TOP` with a variable argument and `TOP` for DML statements has been added since 2005 and require parens.
Mehrdad Afshari
This would be really cool, however, "update top(@N) set systemuserid = @ID where systemuserid is null" gives me "Incorrect syntax near the keyword 'set'".
Moose
Moose: You need to specify the table you want to update after `TOP(n)` clause. Of course, if order is important to you, you should consider Quassnoi's solution anyway.
Mehrdad Afshari
Nevermind, I'm an idiot this morning. Helps to give the table name.
Moose
Thanks Mehdad. Not enough caffiene this morning, need to start the IV drip.
Moose
+8  A: 
WITH    q AS
        (
        SELECT  TOP (@r) *
        FROM    mytable
        ORDER BY
                col1
        )
UPDATE  q
SET     co12 = @value

UPDATE TOP (@r) will work but it will update any @r rows in no particular order.

From the documentation:

The rows referenced in the TOP expression used with INSERT, UPDATE, or DELETE are not arranged in any order. TOP n returns n random rows.

Quassnoi
`@KM`: this time I corrected the statement *before* you pointed :)
Quassnoi
+1, I'm hear to learn, so I try out a lot of code, never saw an UPDATE of an CTE, I'll have to play with that a little...
KM
`@KM`: very useful to delete duplicates. http://explainextended.com/2009/03/14/deleting-duplicates/
Quassnoi
I'm gonna give you a vote because this works too, but I'm not worried about the order. Just need to parcel them out.
Moose