Search This Blog

Friday, October 12, 2012

Transaction SQL Server

SQL Server

BEGIN TRANSACTION

BEGIN TRANSACTION represents a point at which the data referenced by a connection is logically and physically consistent. If errors are encountered, all data modifications made after the BEGIN TRANSACTION can be rolled back to return the data to this known state of consistency. Each transaction lasts until either it completes without errors and COMMIT TRANSACTION is issued to make the modifications a permanent part of the database, or errors are encountered and all modifications are erased with a ROLLBACK TRANSACTION statement.

ROLLBACK TRANSACTION

Rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint inside the transaction. You can use ROLLBACK TRANSACTION to erase all data modifications made from the start of the transaction or to a savepoint. It also frees resources held by the transaction.

COMMIT TRANSACTION

Marks the end of a successful implicit or explicit transaction. If @@TRANCOUNT is 1, COMMIT TRANSACTION makes all data modifications performed since the start of the transaction a permanent part of the database, frees the resources held by the transaction, and decrements @@TRANCOUNT to 0. If @@TRANCOUNT is greater than 1, COMMIT TRANSACTION decrements @@TRANCOUNT only by 1 and the transaction stays active.






Example

begin transaction

update table1
set field1='a'

if @@ERROR <> 0
begin
 rollback transaction
 RAISERROR ('Error table1',16,1)
 return -1
end


update table2
set field3='a'

if @@ERROR <> 0
begin
rollback transaction
RAISERROR ('Error table2',16,1)
return -1
end

commit transaction