How do I update n rows in a table?

。_饼干妹妹 提交于 2019-12-19 06:05:32

问题


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.


回答1:


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

UPDATE TOP(@N) ...



回答2:


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.



来源:https://stackoverflow.com/questions/1487544/how-do-i-update-n-rows-in-a-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!