Executing a stored procedure inside BEGIN/END TRAN

2019-01-22 02:00发布

If I create a Stored Procedure in SQL and call it (EXEC spStoredProcedure) within the BEGIN/END TRANSACTION, does this other stored procedure also fall into the transaction?

I didn't know if it worked like try/catches in C#.

7条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-22 02:15

Yes, everything that you do between the Begin Transaction and Commit (or Rollback) is part of the transaction.

查看更多
够拽才男人
3楼-- · 2019-01-22 02:17

@Chris, I did not know that.

When googling for more info, I came across this - you can set 'savepoints', which can be rolled back to without rolling back the whole transaction.

Could be useful in this situation.

查看更多
等我变得足够好
4楼-- · 2019-01-22 02:24

As Chris and James mentioned, you need to be careful when dealing with nested transactions. There is a set a very good articles on the subject of transactions written by Don Peterson on SQL Server Central , I would recommend having a read of those:

Here there are:

查看更多
小情绪 Triste *
5楼-- · 2019-01-22 02:25

As Chris mentioned, you should be careful about rolling the transaction back.

Specifically this:

IF @@TRANCOUNT > 0 ROLLBACK

is not always what you want. You could do something like this

IF(@@TRANCOUNT = 1) ROLLBACK TRAN
ELSE IF(@@TRANCOUNT > 1) COMMIT TRAN
RETURN @error

This way, the calling proc can inspect the return value from the stored procedure and determine if it wants to commit anyways or continue to bubble up the error.

The reason is that 'COMMIT' will just decrement your transaction counter. Once it decrements the transaction counter to zero, then an actual commit will occur.

查看更多
6楼-- · 2019-01-22 02:26

Sounds great, thanks a bunch. I ended up doing something like this (because I'm on 05)

    BEGIN TRY
       BEGIN TRANSACTION

       DO SOMETHING

       COMMIT
    END TRY
    BEGIN CATCH
      IF @@TRANCOUNT > 0
         ROLLBACK

      -- Raise an error with the details of the exception
      DECLARE @ErrMsg nvarchar(4000), @ErrSeverity int
      SELECT @ErrMsg = ERROR_MESSAGE(),
             @ErrSeverity = ERROR_SEVERITY()

      RAISERROR(@ErrMsg, @ErrSeverity, 1)
    END CATCH
查看更多
倾城 Initia
7楼-- · 2019-01-22 02:26

Yes, all nested stored procedure calls are included in the scope of the transaction. If you are using SQL Server 2005 or greater, you can use Try...Catch as well. Here is more detail on that.

查看更多
登录 后发表回答