You are on page 1of 7

Working with Transactions

BEGIN TRANSACTION

Marks the starting point of an explicit, local transaction. BEGIN TRANSACTION increments
@@TRANCOUNT by 1.

Syntax

BEGIN TRAN [ SACTION ] [ transaction_name | @tran_name_variable


[ WITH MARK [ 'description' ] ] ]

Arguments

transaction_name

Is the name assigned to the transaction. transaction_name must conform to the rules for
identifiers but identifiers longer than 32 characters are not allowed. Use transaction names only
on the outermost pair of nested BEGIN...COMMIT or BEGIN...ROLLBACK statements.

@tran_name_variable

Is the name of a user-defined variable containing a valid transaction name. The variable must be
declared with a char, varchar, nchar, or nvarchar data type.

WITH MARK ['description']

Specifies the transaction is marked in the log. description is a string that describes the mark.

If WITH MARK is used, a transaction name must be specified. WITH MARK allows for
restoring a transaction log to a named mark.

Remarks

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.

BEGIN TRANSACTION starts a local transaction for the connection issuing the statement.
Depending on the current transaction isolation level settings, many resources acquired to support
the Transact-SQL statements issued by the connection are locked by the transaction until it is
1
completed with either a COMMIT TRANSACTION or ROLLBACK TRANSACTION
statement. Transactions left outstanding for long periods of time can prevent other users from
accessing these locked resources.

Although BEGIN TRANSACTION starts a local transaction, it is not recorded in the transaction
log until the application subsequently performs an action that must be recorded in the log, such
as executing an INSERT, UPDATE, or DELETE statement. An application can perform actions
such as acquiring locks to protect the transaction isolation level of SELECT statements, but
nothing is recorded in the log until the application performs a modification action.

Naming multiple transactions in a series of nested transactions with a transaction name has little
effect on the transaction. Only the first (outermost) transaction name is registered with the
system. A rollback to any other name (other than a valid savepoint name) generates an error.
None of the statements executed before the rollback are in fact rolled back at the time this error
occurs. The statements are rolled back only when the outer transaction is rolled back.

BEGIN TRANSACTION starts a local transaction. The local transaction is escalated to a


distributed transaction if the following actions are performed before it is committed or rolled
back:

• An INSERT, DELETE, or UPDATE statement is executed that references a


remote table on a linked server. The INSERT, UPDATE, or DELETE statement
fails if the OLE DB provider used to access the linked server does not support
the ITransactionJoin interface.

• A call is made to a remote stored procedure when the


REMOTE_PROC_TRANSACTIONS option is set to ON.

The local copy of SQL Server becomes the transaction controller and uses MS DTC to manage
the distributed transaction.

Marked Transactions

The WITH MARK option causes the transaction name to be placed in the transaction log. When
restoring a database to an earlier state, the marked transaction can be used in place of a date and
time.

Additionally, transaction log marks are necessary if you need to recover a set of related databases
to a logically consistent state. Marks can be placed in the transaction logs of the related databases
by a distributed transaction. Recovering the set of related databases to these marks results in a set
of databases that are transactionally consistent. Placement of marks in related databases requires
special procedures. More on this point will be covered on chapter 5, Backup and Recovery of
Related Databases.

The mark is placed in the transaction log only if the database is updated by the marked
transaction. Transactions that do not modify data are not marked.

BEGIN TRAN new_name WITH MARK can be nested within an already existing transaction
that is not marked. Upon doing so, new_name becomes the mark name for the transaction,
2
despite the name that the transaction may already have been given. In the following example, M2
is the name of the mark.

BEGIN TRAN T1
UPDATE table1 ...
BEGIN TRAN M2 WITH MARK
UPDATE table2 ...
SELECT * from table1
COMMIT TRAN M2
UPDATE table3 ...
COMMIT TRAN T1

Attempting to mark a transaction that is already marked results in a warning (not error) message:

BEGIN TRAN T1 WITH MARK


UPDATE table1 ...
BEGIN TRAN M2 WITH MARK

Server: Msg 3920, Level 16, State 1, Line 3


WITH MARK option only applies to the first BEGIN TRAN WITH MARK.
The option is ignored.

Permissions

BEGIN TRANSACTION permissions default to any valid user.

Using Variables and Parameters

Transact-SQL has several ways to pass data between Transact-SQL statements. Among these
are:

• Transact-SQL local variables.

A Transact-SQL variable is an object in Transact-SQL batches and scripts that can hold a
data value. After the variable has been declared, or defined, one Transact-SQL statement
in a batch can set the variable to a value and a later statement in the batch can get the
value from the variable. For example:

DECLARE @MYVAR INT


SET @MYVAR=101

SELECT *
FROM DEPARTMENT
WHERE DNO=@MYVAR

DECLARE @MYVAR CHAR(20)


SET @MYVAR='BERUK EWNETU'

SELECT *
FROM DEPARTMENT

3
WHERE DHEAD=@MYVAR

• Transact-SQL parameters.

A parameter is an object used to pass data between a stored procedure and the batch or
script that executes the stored procedure. Parameters can be either input or output
parameters. For example:

CREATE PROCEDURE ParmSample @EmpIDParm INT AS


SELECT *
FROM Employees
WHERE EmployeeID = @EmpIDParm
GO

EXEC ParmSample @EmpIDParm = 1234


GO

Examples

A. Naming a transaction

This example demonstrates how to name a transaction. Upon committing the named transaction,
royalties paid for all popular computer books are increased by 10 percent.

DECLARE @TranName VARCHAR(20)


SELECT @TranName = 'MyTransaction'

BEGIN TRANSACTION @TranName


UPDATE DEPARTMENT
SET DHEAD= 'FIREHIWOT FITSUM'
WHERE DNO='120'

COMMIT TRANSACTION MyTransaction

DECLARE @Tran1 VARCHAR(20)


SELECT @Tran1 = 'MyNEWTransaction'

BEGIN TRANSACTION @Tran1


UPDATE DEPARTMENT
SET DHEAD= 'ZELEALEM FIKER'
WHERE DNO='120'

COMMIT TRANSACTION MyNEWTransaction

4
DECLARE @TranName VARCHAR(20)
SELECT @TranName = 'MyTransaction'

BEGIN TRANSACTION @TranName


insert into department
values('225','ECONOMICS','FITSUM WORKNEH','4k')
COMMIT TRAN MyTransaction

DECLARE @TranName VARCHAR(20)


SELECT @TranName = 'MyTransaction'

BEGIN TRANSACTION @TranName


DELETE FROM DEPARTMENT
WHERE DNO='225'
COMMIT TRAN MyTransaction

DECLARE @TranName VARCHAR(20)


SELECT @TranName = 'ChangeDloc'
BEGIN TRANSACTION @TranName
UPDATE DEPARTMENT
SET DLOCATION='NEW'
WHERE DNO IN(
SELECT DNO
FROM DEPARTMENT
WHERE DNO>110 )
COMMIT TRAN ChangeDloc

B. Marking a transaction

This example demonstrates how to mark a transaction. The transaction named "RoyaltyUpdate"
is marked.

BEGIN TRANSACTION DheadUpdate


WITH MARK 'Update Dhead values'

USE STUDENT

UPDATE DEPARTMENT
SET DHEAD = 'ADDIS ABABA'
WHERE DNAME LIKE 'N%'

5
COMMIT TRANSACTION DheadUpdate

COLLISION IN TRANSACTION
DheadUpdate DeptDelete
BEGIN TRANSACTION DheadUpdate

USE STUDENT
UPDATE DEPARTMENT
SET DHEAD = 'ADDIS ABABA'
WHERE DNAME LIKE 'N%'

BEGIN TRANSACTION DeptDelete

USE STUDENT
DELETE FROM DEPARTMENT
WHERE DNAME LIKE 'N%'

COMMIT TRANSACTION DeptDelete


COMMIT TRANSACTION DheadUpdate

COMMIT TRANSACTION

Marks the end of a successful implicit or user-defined 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 connection, and
decrements @@TRANCOUNT to 0. If @@TRANCOUNT is greater than 1, COMMIT
TRANSACTION decrements @@TRANCOUNT only by 1.

Syntax

COMMIT [ TRAN [ SACTION ] [ transaction_name | @tran_name_variable ] ]

Arguments

transaction_name

Is ignored by Microsoft® SQL Server™. transaction_name specifies a transaction name


assigned by a previous BEGIN TRANSACTION. transaction_name must conform to the rules
for identifiers, but only the first 32 characters of the transaction name are used.
transaction_name can be used as a readability aid by indicating to programmers which nested
BEGIN TRANSACTION the COMMIT TRANSACTION is associated with.

@tran_name_variable

Is the name of a user-defined variable containing a valid transaction name. The variable must be
declared with a char, varchar, nchar, or nvarchar data type.

6
ROLLBACK TRANSACTION

Rolls back an explicit or implicit transaction to the beginning of the transaction, or to a savepoint
inside a transaction.

Syntax

ROLLBACK [ TRAN [ SACTION ]


[ transaction_name | @tran_name_variable
| savepoint_name | @savepoint_variable ] ]

Arguments

transaction_name

Is the name assigned to the transaction on BEGIN TRANSACTION. transaction_name must


conform to the rules for identifiers, but only the first 32 characters of the transaction name are
used. When nesting transactions, transaction_name must be the name from the outermost
BEGIN TRANSACTION statement.

@tran_name_variable

Is the name of a user-defined variable containing a valid transaction name. The variable must be
declared with a char, varchar, nchar, or nvarchar data type.

savepoint_name

Is savepoint_name from a SAVE TRANSACTION statement. savepoint_name must conform to


the rules for identifiers. Use savepoint_name when a conditional rollback should affect only part
of the transaction.

@savepoint_variable

Is name of a user-defined variable containing a valid savepoint name. The variable must be
declared with a char, varchar, nchar, or nvarchar data type.

You might also like