Is T-SQL Stored Procedure Execution 'atomic'?

后端 未结 5 1900
甜味超标
甜味超标 2021-01-04 01:16

Let\'s say I have a simple stored procedure that looks like this (note: this is just an example, not a practical procedure):

CREATE PROCEDURE incrementCounte         


        
5条回答
  •  滥情空心
    2021-01-04 02:08

    This is for SQL Server.

    Each statement is atomic, but if you want the stored procedure to be atomic (or any sequence of statements in general), you need to explicitly surround the statements with

    BEGIN TRANSACTION
    Statement ...
    Statement ...
    COMMIT TRANSACTION

    (It's common to use BEGIN TRAN and END TRAN for short.)

    Of course there are lots of ways to get into lock trouble depending what else is going on at the same time, so you may need a strategy for dealing with failed transactions. (A complete discussion of all the circumstances that might result in locks, no matter how you contrive this particular SP, is beyond the scope of the question.) But they will still be resubmittable because of the atomicity. And in my experience you'll probably be fine, without knowing about your transaction volumes and the other activities on the database. Excuse me for stating the obvious.

    Contrary to a popular misconception, this will work in your case with default transaction level settings.

提交回复
热议问题