如何在 UPDATE 语句上创建一个循环,该循环一直工作到没有行可供更新为止?
假设我有数千行需要更新。
我计划迭代地进行更新;每次迭代仅更新 1000 行。
我想迭代直到没有行需要更新。
如何运行下面的 T-SQL 脚本直到没有要更新的行?
-- TODO: Create a loop so that it exists when there is no ROW left to be updated;
-- how can I do it?
UPDATE tableToUpdate
SET IsVegetable = 1
WHERE Id IN
(SELECT TOP 1000 Id
FROM tableToUpdate
WHERE Date = '2011-07-23 14:00')
-- Loop ends
Assume that I have thousands of rows to update.
And I plan to do the update iteratively; by only updating 1000 rows per iteration.
And I want to iterate until there are no rows left to update.
How can I run the T-SQL script below until there is no row to update?
-- TODO: Create a loop so that it exists when there is no ROW left to be updated;
-- how can I do it?
UPDATE tableToUpdate
SET IsVegetable = 1
WHERE Id IN
(SELECT TOP 1000 Id
FROM tableToUpdate
WHERE Date = '2011-07-23 14:00')
-- Loop ends
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尝试这个循环
为什么 ISNULL - 因为尚不清楚 - IsVegetable 字段是否可为空,如果不是 - 则不需要 ISNULL
当 IsVegetable 中不会留下任何行时<> 1 - 循环将退出,因为 @@ROWCOUNT 将 = 0 或 < 1000(最后一次迭代)
Try this loop
Why ISNULL - because it is not clear - if the field IsVegetable is nullable or not, if not - then ISNULL not needed
When there no rows will left with IsVegetable <> 1 - the loop will quit because the @@ROWCOUNT will be = 0 or < 1000 (for the last iteration)