SQL Server : stored procedure transaction

前端 未结 4 1415
时光说笑
时光说笑 2020-12-28 15:45

Hello I got some stored procedures to create products and other stuff on my site. Now I have to run some of them in a transaction. Is that possible or do I have to make a st

4条回答
  •  难免孤独
    2020-12-28 16:08

    To add to the other answers above, you may want to add some error handling:

    BEGIN TRAN
    
    BEGIN TRY
    
       EXEC P1
    
       EXEC P2
    
       COMMIT TRAN
    
    END TRY
    BEGIN CATCH
    
      ROLLBACK TRAN
    
    END CATCH
    

    Update with C# code (I personally find it a lot easier to keep trans code out of the sprocs and in the data layer - makes composing stored procedures easier at a later stage):

    using (var conn = new SqlConnection(...))
    
        trans = conn.BeginTransaction();
    
        try
       {
           ...call P1 using transaction
           ...call P2 using transaction
    
           trans.Commit();
       }
       catch
       {
           trans.RollBack();
           throw;
       }
    }
    

提交回复
热议问题