TSQL Try / Catch within Transaction or vice versa?

后端 未结 3 1676
梦如初夏
梦如初夏 2020-11-30 04:06

I\'m writing a script that will delete records from a number of tables, but before it deletes it must return a count for a user to confirm before committing.

This is

3条回答
  •  执念已碎
    2020-11-30 04:44

    Only open a transaction once you are inside the TRY block and just before the actual statement, and commit it straightaway. Do not wait for your control to go to the end of the batch to commit your transactions.

    If something goes wrong while you are in the TRY block and you have opened a transaction, the control will jump to the CATCH block. Simply rollback your transaction there and do other error handling as required.

    I have added a little check for any open transaction using @@TRANCOUNT function before actually rolling back the transaction. It doesn't really make much sense in this scenario. It is more useful when you are doing some validations checks in your TRY block before you open a transaction like checking param values and other stuff and raising error in the TRY block if any of the validation checks fail. In that case, the control will jump to the CATCH block without even opening a transaction. There you can check for any open transaction and rollback if there are any open ones. In your case, you really don't need to check for any open transaction as you will not enter the CATCH block unless something goes wrong inside your transaction.

    Do not ask after you have executed the DELETE operation whether it needs to be committed or rolled back; do all these validation before opening the transaction. Once a transaction is opened, commit it straightaway and in case of any errors, do error handling (you are doing a good job by getting detailed info by using almost all of the error functions).

    BEGIN TRY
    
      BEGIN TRANSACTION SCHEDULEDELETE
        DELETE   -- delete commands full SQL cut out
        DELETE   -- delete commands full SQL cut out
        DELETE   -- delete commands full SQL cut out
     COMMIT TRANSACTION SCHEDULEDELETE
        PRINT 'X rows deleted. Operation Successful Tara.' --calculation cut out.
    END TRY
    
    BEGIN CATCH 
      IF (@@TRANCOUNT > 0)
       BEGIN
          ROLLBACK TRANSACTION SCHEDULEDELETE
          PRINT 'Error detected, all changes reversed'
       END 
        SELECT
            ERROR_NUMBER() AS ErrorNumber,
            ERROR_SEVERITY() AS ErrorSeverity,
            ERROR_STATE() AS ErrorState,
            ERROR_PROCEDURE() AS ErrorProcedure,
            ERROR_LINE() AS ErrorLine,
            ERROR_MESSAGE() AS ErrorMessage
    END CATCH
    

提交回复
热议问题