t-sql:按照“in”确定的特定顺序更新表达
假设:
declare @counter int
set @counter = 0
update MyTable
set @counter = MyField = @counter + 1
where Some_ID in (select ID from SomeTable)
我想要的是更新发生的顺序与返回 select ID from SomeTable
ID 的顺序相同。有没有一个好的方法来做到这一点?
Suppose:
declare @counter int
set @counter = 0
update MyTable
set @counter = MyField = @counter + 1
where Some_ID in (select ID from SomeTable)
What I want is that update happened in same order as select ID from SomeTable
IDs are returned. Is there a nice way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
以下是使用带有
ROW_NUMBER
的 CTE 的解决方案...您可以确定希望SomeTable
中的记录在OVER
子句中返回的顺序代码>ROW_NUMBER。Here's a solution using a CTE with
ROW_NUMBER
... you determine the order that you want the records fromSomeTable
returned in theOVER
clause ofROW_NUMBER
.假设您希望在更新的记录中有一列包含递增的数字,我认为唯一的方法是获取 ID 列表并进行多次更新。
在 SQL Server 中,您可能会使用游标来执行此操作。
Assuming you want to have a column containing an incrementing number in the updated records I think the only way you could do this is to get the list of IDs and do a number of updates.
In SQL server you would likely do this using a cursor.