sql server 2008更新选择threadsafe?

时间:2012-08-24 12:55:42

标签: sql

UPDATE dbo.A  
  SET StatusCode = 'booked' 
   , UpdateDate = GETDATE()
 OUTPUT INSERTED.id INTO @TableVar
 WHERE id = ( 
     SELECT TOP 1 wq.id
     FROM dbo.A AS wq
     WHERE wq.statusCode = 'Claimed' and wq.id = 2

)

我需要更新表A,其中id等于2且statusCode等于'已申请'更新为'已预订'

它是线程安全的吗? TKS

1 个答案:

答案 0 :(得分:5)

通过将with (updlock, holdlock)添加到子查询中,可以提高并发安全性:

FROM dbo.A AS wq with (updlock, holdlock)

等效的方法是将语句包装在repeatable read transaction

REPEATABLE READ
Specifies that statements cannot read data that has been modified but not yet 
committed by other transactions and that no other transactions can modify data 
that has been read by the current transaction until the current transaction 
completes.

这看起来像:

set transaction isolation level repeatable read
start transaction
... your query here ...
commit transaction