I'm having trouble using a transaction - rollback statement in sql. I can't seem to have the rollback executed during an error when i've altered a table to add a column with the same name (run the alter script twice on purpose to test the rollback). Somehow i got an error of the column should be unique (since the column already added during the 1st execution of the script). I want the sql execution to display the Failed instead and rollback the transaction. My code is as follows:
Expand|Select|Wrap|Line Numbers
- BEGIN TRANSACTION
- ALTER TABLE dbo.tbl_name
- ADD [column1] [varchar] (20) NULL
- -----------------------------------------------
- --Error handling
- IF @@Error = 0
- Begin
- COMMIT TRANSACTION
- print '-Success'
- END
- ELSE
- Begin
- ROLLBACK TRANSACTION
- print '-Failed'
- End
- GO