如何使用 ms sql 进行更新和排序
理想情况下,我想这样做:
UPDATE TOP (10) messages SET status=10 WHERE status=0 ORDER BY priority DESC;
用英语:我想从数据库获取前 10 条可用(状态 = 0)消息并锁定它们(状态 = 10)。 应首先获取优先级较高的消息。
不幸的是,MS SQL 不允许在更新中使用 order by 子句。
无论如何如何规避这个?
Ideally I want to do this:
UPDATE TOP (10) messages SET status=10 WHERE status=0 ORDER BY priority DESC;
In English: I want to get the top 10 available (status=0) messages from the DB and lock them (status=10). A message with a higher priority should be gotten first.
unfortunately MS SQL doesn't allow an order by clause in the update.
Anyway how to circumvent this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您可以执行一个子查询,首先获取按优先级排序的前 10 个 ID,然后更新该子查询中的 ID:
You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:
我必须将其作为一种更好的方法提供 - 您并不总是拥有身份字段的奢侈:
您还可以根据需要使子查询变得复杂 - 连接多个表等...
为什么这更好? 它不依赖于
messages
表中是否存在标识字段(或任何其他唯一列)。 它可用于更新任何表中的前 N 行,即使该表根本没有唯一键。I have to offer this as a better approach - you don't always have the luxury of an identity field:
You can also make the sub-query as complicated as you want - joining multiple tables, etc...
Why is this better? It does not rely on the presence of an identity field (or any other unique column) in the
messages
table. It can be used to update the top N rows from any table, even if that table has no unique key at all.正如下面的注释中所述,您还可以使用 SET ROWCOUNT 子句,但仅适用于 SQL Server 2014 及更早版本。
详细信息:http://msdn.microsoft.com/en-us/library /ms188774.aspx
或者使用临时表
As stated in comments below, you can use also the SET ROWCOUNT clause, but just for SQL Server 2014 and older.
More info: http://msdn.microsoft.com/en-us/library/ms188774.aspx
Or with a temp table