Correct use of transactions in SQL Server

后端 未结 3 544
北恋
北恋 2020-11-28 17:20

I have 2 commands and need both of them executed correctly or none of them executed. So I think I need a transaction, but I don\'t know how to use it correctly.

What

3条回答
  •  再見小時候
    2020-11-28 17:55

    Add a try/catch block, if the transaction succeeds it will commit the changes, if the transaction fails the transaction is rolled back:

    BEGIN TRANSACTION [Tran1]
    
      BEGIN TRY
    
          INSERT INTO [Test].[dbo].[T1] ([Title], [AVG])
          VALUES ('Tidd130', 130), ('Tidd230', 230)
    
          UPDATE [Test].[dbo].[T1]
          SET [Title] = N'az2' ,[AVG] = 1
          WHERE [dbo].[T1].[Title] = N'az'
    
          COMMIT TRANSACTION [Tran1]
    
      END TRY
    
      BEGIN CATCH
    
          ROLLBACK TRANSACTION [Tran1]
    
      END CATCH  
    

提交回复
热议问题