如何从数据库中选择记录并通过原子查询对其进行更新

|| 我在带有“状态”列的表中有许多记录,我想选择“状态=待处理”的单个记录,并在同一原子查询中将其标记为“状态=处理中”。最好的方法是什么? 这是必需的,因为可以同时运行多个查询以尝试处理这些记录,并且我不希望两个线程选择相同的记录进行处理。
已邀请:
您可以使用OUTPUT子句:
UPDATE [table]
SET Status = \'InProcess\'
OUTPUT deleted.*
WHERE Status = \'Pending\'
如果您想获得具有新状态的行或在旧状态下删除该行,则可以在此处使用插入的表名。
这是有关使用表作为队列的文章。 这张桌子
create table T (ID int identity, Status varchar(15))
这样的事情应该可以避免死锁。
;with cte as
(
  select top 1 *
  from T with (rowlock, readpast)
  where Status = \'Pending\'
  order by ID
)
update cte
set Status = \'InProcess\'
output inserted.ID, inserted.Status
这应该可以解决问题
UPDATE [table]
SET Status = \'InProcess\'
WHERE Status = \'Pending\'
SQL 2008应该为您进行任何锁定。
以下内容是一种hack,但它对我来说可以进行原子读取/更新:
declare temp1, temp2, ...;
update table
   set temp1=column1,
       temp2=column2, ... 
       column1=expression1,
       column2=expression2, ...
where conditions;
select temp1, temp2, ...;

要回复问题请先登录注册