I need to update the first N rows in a table meeting a condition.
我需要更新满足条件的表中的前N行。
I know I can do an Update Top N... but the problem is that N is in a @variable.
我知道我可以做一个Update Top N ...但问题是N在@variable中。
UPDATE TOP @N SET ... doesn't work.
更新顶部@N SET ...不起作用。
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.
这里没有特定的表定义,因为列是什么并不重要。如果我可以为一个列表执行此操作,我可以为我的表执行此操作。
2 个解决方案
#1
16
You need to use parens after TOP
clause when you want to use a variable:
当你想使用变量时,你需要在TOP子句之后使用parens:
UPDATE TOP(@N) ...
#2
10
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.
UPDATE TOP(@r)将起作用,但它将以任何特定顺序更新任何@r行。
From the documentation:
从文档:
The rows referenced in the
TOP
expression used withINSERT
,UPDATE
, orDELETE
are not arranged in any order.TOP n
returnsn
random rows.与INSERT,UPDATE或DELETE一起使用的TOP表达式中引用的行不按任何顺序排列。 TOP n返回n个随机行。
#1
16
You need to use parens after TOP
clause when you want to use a variable:
当你想使用变量时,你需要在TOP子句之后使用parens:
UPDATE TOP(@N) ...
#2
10
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.
UPDATE TOP(@r)将起作用,但它将以任何特定顺序更新任何@r行。
From the documentation:
从文档:
The rows referenced in the
TOP
expression used withINSERT
,UPDATE
, orDELETE
are not arranged in any order.TOP n
returnsn
random rows.与INSERT,UPDATE或DELETE一起使用的TOP表达式中引用的行不按任何顺序排列。 TOP n返回n个随机行。