Lock in SQL Server Stored Procedure

I have a stored procedure that manipulates an integer table field (which represents a serial number) based on some criteria - the criteria can reset the field back to zero. In a multi-user environment, there is a possibility that 1 user can refer to the field before it is updated by another user, so I would like to prevent this by limiting the stored procedure to only 1 user at a time. Is there a way to do this in my stored procedure?

+3
source share
1 answer

If you conclude your transactions inside a transaction, all of them will be executed atomically. You may need to increase the level of transaction isolation based on your needs.

For example, if you do not want anyone to read or write any particular table while executing a bunch of statements, this statement at the top will do this:

SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;

I do not recommend escalating to this level if it is absolutely necessary because it basically violates the benefits of concurrency.

Instead, consider using something lower or remaking your logic to remove the need for a critical section.

+7
source

All Articles