简体   繁体   中英

Is this SQL Statement Safe for Concurrent Access?

Is the SQL statement below 'safe' for concurrent access? At what point will A get locked? If it's just before the INSERT is there a chance that the first @count may be wrong?

BEGIN TRAN;
    SELECT @count = count(1) from A
    DELETE FROM A where x=z
    SELECT @newCount = count(1) from A
    SELECT @newCount - @count
COMMIT TRAN;
BEGIN TRAN;
    DECLARE @RC INT
    EXEC @RC = sp_getapplock @Resource='ArchiveLock', @LockMode='Exclusive',  @LockOwner='Transaction', @LockTimeout=15000
    SELECT @count = count(1) from A
    DELETE FROM A where x=z
    SELECT @newCount = count(1) from A
    SELECT @newCount - @count
COMMIT TRAN;

Try this. I used this recently to handle set of Delet statements which are called by multiple processes in parallel. The sp_getapplock creates a lock until the transaction is committed which makes other process to wait.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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