Intro

A transaction is a sequence of operations which must complete in entirety or not at all. If the transaction fails for any reason, the databases involved are rolled back, i.e. returned to their original state. This insures the integrity of a database, especially for systems where multiple users and processes may try to access the same data at the same time.

Transactions in databases should pass the ACID test:

Transactions on data in a SQL Server database are usually handled with T-SQL or with DB APIs. It is not good practice to mix the two.

In SQL Server there are three ways to start a transaction:

When transaction completes, it must end with either a COMMIT or ROLLBACK statement. If the client's connection, application, or either computer unexpectedly stops during a transaction, then the transaction is rolled back.

This paragraph from the MSDN Library is so concise that I haven't bothered to paraphrase it much:

All T-SQL statements are allowed in transactions except for the following:

ALTER DATABASE LOAD DATABASE
BACKUP LOG LOAD TRANSACTION
CREATE DATABASE RECONFIGURE
DISK INIT RESTORE DATABASE
DROP DATABASE RESTORE LOG
DUMP TRANSACTION UPDATE STATISTICS

SQL Server can also work with MS DTC (Microsoft Distributed Transaction Coordinator) for distributed transactions. The SQL keywords of BEGIN DISTRIBUTED TRANSACTION would have to be used.

Examples

Example 1

Here is a simple example of using explicit transactions in SQL Server.

BEGIN TRANSACTION myTrans--Do a bunch of stuff. --Check if it's OK to commit:
IF @myOK = 1
  COMMIT TRANSACTION myTrans
ELSE
  ROLLBACK TRANSACTION myTrans

Example 2

A Savepoint can be used for a partial rollback.

BEGIN TRANSACTION myTrans--Do a bunch of stuff that is certain. SAVE TRANSACTION mySavepoint--Do a bunch of stuff that may err. --Check if it's OK to commit:
IF @@ERROR <> 0
BEGIN
  COMMIT TRANSACTION myTrans
  RETURN 0
END
ELSE
BEGIN
  ROLLBACK TRANSACTION mySavepoint
  RETURN @@ERROR
END

Page Modified: (Hand noted: 2007-10-13 19:44:50Z) (Auto noted: 2007-11-17 06:43:49Z)