views:

44

answers:

1

hi,

i need to update a database where some of the table have changed (columns have been added). I want to perform this action in a proper transaction. If the code executes without any problem then i will commit the changes otherwise i will rollback the database back to its original state.

I want to do something like this:

BEGIN TRANSACTION
    ...Execute some sql statements here
COMMIT TRANSACTION (When every thing goes well)
ROLLBACK TRANSACTION (When something goes wrong)

Please tell me what is the best way to do this i know there is a @@TranCount variable but dont know its exact purpose.

Thanks.

+1  A: 
Begin Transaction

Alter Table dbo.MyTable
Add Col1 varchar(50)

If @@Error = 0

   Begin
    Commit Transaction
   End
Else
   Begin
    Rollback Transaction
   End

@@Error gets reset after each SQL Statement so you must check it immediately after each statement has been executed to check for any errors.

Barry