简体   繁体   English

我是否需要事务/锁用于SQL Server中的此并发更新方案

[英]Do I need transactions/locks for this concurrent update scenario in SQL Server

I am wondering whether I really do need transactions/locks in the following scenario. 我想知道在以下情况下我是否真的需要事务/锁。 I can carry out 3 operations which might be concurrent in any number of them (ie I could have two Task 1 running and three Task 2 running): 我可以执行3个操作,这些操作可以同时执行任意数量(即,我可以同时运行两个任务1和三个任务2):

Task 1: 任务1:

select distinct count(some_id) as my_counter from table_1;
update table_2 set counter = my_counter;

Task 2: 任务2:

insert into table_1 ...;
update table_2 set counter = counter + 1;

Task 3: 任务3:

delete from table_1 where id = ...;
update table_2 set counter = counter - 1;

How should I implement the above being sure that I will never corrupt table_2's field counter ? 我应该如何实现上面的内容以确保我不会破坏table_2的字段counter

Thank you very much! 非常感谢你!

A few points: 几点:

  • In any case you need to enclose the two statements of each task in a transaction. 无论如何,您都需要将每个任务的两个语句包含在事务中。
  • I think you need serializable transaction isolation level. 我认为您需要可序列化的事务隔离级别。 Anything less will not do. 少做不到。 For example using "repeatable read" task 1 might set table_2.counter to a stale value. 例如,使用“重复读取”任务1可能会将table_2.counter设置为陈旧值。
  • You need to always access table_1 before table_2. 您需要始终在table_2之前访问table_1。 This will ensure a consistent lock-ordering preventing deadlocks. 这将确保一致的锁顺序,防止死锁。

you can use TRIGGER for Task 2,3. 您可以将TRIGGER用于任务2,3。 it locks you tables in appropriate way. 它以适当的方式锁定表。 for Task 1 you should use XLOCK for row lock in your transaction 对于Task 1您应该在事务中使用XLOCK进行行锁定

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

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