如何更新TOP 400?
我想更新数据库表中的前 400 行。伪SQL如下,我该怎么做?
UPDATE top (400) db.dbo.tbl
SET column1 = 2
WHERE column2 = 1
AND column1 is null
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
但我不喜欢这样,因为无法保证哪个是前 400 名,您可能需要添加一些其他类型的标准。甚至还有子查询的 Order By。
But I don't like this as there's no way to guarantee WHICH top 400, you might want to add some other type of criteria. And even an Order By to the subquery.
如何确定前 400 名?如果没有 order by,就无法保证始终选择同一组,因此可能会更新错误的记录。
How would you determine the top 400? With no order by there is no guanantee that the same set would always be selected and thus the wrong records could be updated.
您可能正在寻找类似这样的内容:
其中 ID 是表的主键列。
You're probably looking for something like this:
where ID is the primary key column of the table.
如果您使用的是 SQL Server 2008,“top n”语法将适用于删除和更新语句。否则,此处列出的用于标识子查询或派生表中主键的其他方法也可以很好地工作。正如其他人所做的那样,强烈建议使用“order by”,否则您更新的行可能会因一个查询而异。
If you're using SQL Server 2008, the "top n" syntax will work on delete and update statements. Otherwise, the other methods listed here where you identify the primary keys in a subquery or derived table will work well. And as others have done, the "order by" is highly recommended or the rows you update can differ from one query to the next.
您可以使用以下语法
UPDATE top (400) tbl
设置列 1 = '2'
其中第 2 列 = '1'
并且column1为空
请参阅这篇文章http://balasingam.com/sql-server/update-top-n-record-in-sql-server/comment-page-1#comment-227
You can use following syntax
UPDATE top (400) tbl
SET column1 = '2'
WHERE column2 = '1'
AND column1 is null
See this post http://balasingam.com/sql-server/update-top-n-record-in-sql-server/comment-page-1#comment-227