How to commit and rollback transaction in sql server?

前端 未结 3 770
自闭症患者
自闭症患者 2020-12-05 05:50

I have a huge script for creating tables and porting data from one server. So this sceipt basically has -

  1. Create statements for tables.
  2. Insert for po
相关标签:
3条回答
  • 2020-12-05 06:11

    Don't use @@ERROR, use BEGIN TRY/BEGIN CATCH instead. See this article: Exception handling and nested transactions for a sample procedure:

    create procedure [usp_my_procedure_name]
    as
    begin
        set nocount on;
        declare @trancount int;
        set @trancount = @@trancount;
        begin try
            if @trancount = 0
                begin transaction
            else
                save transaction usp_my_procedure_name;
    
            -- Do the actual work here
    
    lbexit:
            if @trancount = 0   
                commit;
        end try
        begin catch
            declare @error int, @message varchar(4000), @xstate int;
            select @error = ERROR_NUMBER(), @message = ERROR_MESSAGE(), @xstate = XACT_STATE();
            if @xstate = -1
                rollback;
            if @xstate = 1 and @trancount = 0
                rollback
            if @xstate = 1 and @trancount > 0
                rollback transaction usp_my_procedure_name;
    
            raiserror ('usp_my_procedure_name: %d: %s', 16, 1, @error, @message) ;
            return;
        end catch   
    end
    
    0 讨论(0)
  • 2020-12-05 06:14

    As per http://msdn.microsoft.com/en-us/library/ms188790.aspx

    @@ERROR: Returns the error number for the last Transact-SQL statement executed.

    You will have to check after each statement in order to perform the rollback and return.

    Commit can be at the end.

    HTH

    0 讨论(0)
  • 2020-12-05 06:21

    Avoid direct references to '@@ERROR'. It's a flighty little thing that can be lost.

    Declare @ErrorCode int;
    ... perform stuff ...
    Set @ErrorCode = @@ERROR;
    ... other stuff ...
    if @ErrorCode ...... 
    
    0 讨论(0)
提交回复
热议问题