简体   繁体   English

如何确保仅“应用”了一个更新?

[英]How do I make sure only one update is “applied”?

Let's say I define a table like so: 假设我这样定义一个表:

create table anonymized_example(
  id bigint IDENTITY(1,1) PRIMARY KEY,
  status varchar(50) not null,
  other_columns varchar(50));

Now, sometimes to threads in a cluster may want to update this table at the same time. 现在,有时集群中的线程可能要同时更新此表。 My idea is to run a query like this: 我的想法是运行这样的查询:

update reservation_proxy_order,
set status='WORKING_ON_IT',
where id=?,
and status <> 'WORKING_ON_IT';

As far as I understand, this means that one of the threads will get to update first, and return out that 1 row was updated, and the other(s) will report that they updated 0 rows. 据我了解,这意味着其中一个线程将首先进行更新,并返回已更新的1行,而其他线程将报告已更新0行。 And that's great. 那太好了。 Now one thread in the cluster will start doing it's thing, and the rest will be left alone. 现在,集群中的一个线程将开始执行此操作,其余线程将被保留。

However, there's something that doesn't sit quite right with me. 但是,有些事情与我不对。 Is this a valid way to do this? 这是这样做的有效方法吗? Or are there better ways that should be considered? 还是应该考虑更好的方法?

Yes and status <> 'WORKING_ON_IT should assure that only the first update is applied. and status <> 'WORKING_ON_IT应确保仅应用第一次更新。 (0 row(s) affected) means nothing was changed. (0 row(s) affected)表示未进行任何更改。

Test for yourself by running it multiple times. 通过多次运行来测试自己。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM