begin transaction sql 1

begin transaction sql

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  

Here is what the above code is Doing:
1. It’s creating a transaction named Tran1
2. It’s inserting two rows into the table T1
3. It’s updating the row with Title = ‘az’
4. It’s committing the transaction
5. If any of the above steps fail, it’s rolling back the transaction

The above code is a good example of how to use transactions in SQL Server.

The following code is a bad example of how to use transactions in SQL Server:

Similar Posts