SQL Server: how to acquire exclusive lock to prevent race condition?

前端 未结 2 644
野的像风
野的像风 2021-01-14 17:46

I have the following T-SQL code:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE
BEGIN TRANSACTION T1_Test

    /*This is a dummy table used for \"locking\" 
           


        
相关标签:
2条回答
  • 2021-01-14 18:21

    You can use the locking hint WITH(XLOCK, ROWLOCK) within the scope of a transaction with Repeatable Read isolation. At Serializable isolation the exclusive lock is obtained by default on a read operation, so if you needed a particular transaction to play nice in parallel, you could specify an increased serialization level for that one transaction when creating it (which you are doing; this isn't a hack, just the way things are done depending on the situation).

    0 讨论(0)
  • 2021-01-14 18:34

    I'm not exactly sure what you are trying to do from the posted code. I presume you are just trying to serialize access to that piece of code? If so sp_getapplock should do what you need instead of creating a new dummy table that you just use to take locks on.

    Details here

    0 讨论(0)
提交回复
热议问题