Upload
divandann
View
229
Download
0
Embed Size (px)
Citation preview
8/14/2019 16-Transaction Management in SQL Server
1/24
Transaction Management inTransaction Management in inin SQLSQL
Server 2005Server 2005
2
Log in SQL ServerLog in SQL Server
The log (or transaction log) is implemented as aseparate file or set of files in the database. The logcache is managed separately from the buffer cachefor data pages
The format of log records and pages is notconstrained to follow the format of data pages.
The transaction log can be implemented in severalfiles. The files can be defined to expand automaticallyby setting the FILEGROWTH value for the log.
3
Use of the Log at StartupUse of the Log at Startup
When SQL Server is started, the log is used toperform a warm restart (or recovery)
This is done in case the SQL Server process wasstopped by a failure
In this case in fact the databases may be left in astate where some modifications were never writtenfrom the buffer cache to the data files, and there maybe some modifications from incomplete transactionsin the data files.
4
Log Logical ArchitectureLog Logical Architecture
Each log record is identified by a log sequencenumber (LSN). Each new log record is written to thelogical end of the log with an LSN that is higher than
the LSN of the record before it.
Each log record contains the ID of the transactionthat it belongs to. For each transaction, all logrecords associated with the transaction areindividually linked in a chain using backward pointersthat speed the rollback of the transaction.
8/14/2019 16-Transaction Management in SQL Server
2/24
5
Operations Recorded in the logOperations Recorded in the log
The start and end of each transaction.
Every data modification (insert, update, or delete).This includes changes to system tables made bysystem stored procedures or data definition language(DDL) statements.
Every extent and page allocation or deallocation.
Creating or dropping a table or index.
6
MinLSNMinLSN, Active Log, Active Log
The Minimum Recovery LSN (MinLSN) is the LSN ofthe first log record that must be present for a
successful recovery. MinLSN is the minimum of the:
LSN of the start of the checkpoint
LSN of the start of the oldest transaction in theUNDO and REDO sets
The part of the log from MinLSN to the last record iscalled the active log
This is the section of the log required to do arecovery of the database. No part of the active logcan ever be truncated.
7
MinLSNMinLSN
At the time that the recorded checkpoint at LSN 147was processed, Tran 1 had been committed and Tran2 was the only active transaction.
That makes B(Tran2) the start of the oldesttransaction active at the time of the last checkpoint
(oldest transaction in the UNDO and REDO sets).This makes LSN 142, the B(Tran 2), the MinLSN.
8
CheckpointCheckpoint
A checkpoint performs the following processes:
Writes a record to the log file marking the start of thecheckpoint.
Stores information recorded for the checkpoint in a chain ofcheckpoint log records. One piece of information is theMinLSN. Another piece of information is a list of all theactive transactions that have modified the database.
Writes all dirty log and data pages to disk.
Writes a record marking the end of the checkpoint to the logfile.
Writes the LSN of the start of this chain to the database boot
page
8/14/2019 16-Transaction Management in SQL Server
3/24
8/14/2019 16-Transaction Management in SQL Server
4/24
13
LogLog
When the database is created, the logical log filebegins at the start of the physical log file.
New log records are added at the end of the logicallog and expand toward the end of the physical log.
Log records in the virtual logs that appear in front ofMinLSN are deleted with a truncation operation.
14
LogLog
The transaction log is a wrap-around file: when theend of the logical log reaches the end of the physicallog file, the new log records wrap around to the startof the physical log file.
15
LogLog
This cycle repeats endlessly, as long as the end ofthe logical log never reaches the beginning of thelogical log.
If the old log records are truncated frequently enoughto always leave sufficient room for all the new logrecords created from the last checkpoint, the lognever fills.
If the log contains multiple physical log files, thelogical log will move through all the physical log filesbefore it wraps back to the start of the first physical
log file.
16
LogLog
If the end of the logical log does reach the start of thelogical log, one of two things occurs:
If the FILEGROWTH setting is enabled for the logand space is available on the disk, the file isextended by the amount specified ingrowth_incrementand the new log records areadded to the extension.
If the FILEGROWTH setting is not enabled, or thedisk that is holding the log file has less free spacethan the amount specified in growth_increment, an
9002 error is generated.
8/14/2019 16-Transaction Management in SQL Server
5/24
8/14/2019 16-Transaction Management in SQL Server
6/24
21
SimpleSimple RecoveryRecovery ModelModel
Because the transaction log is not backed up, thesimple recovery model risks significant work-loss
exposure if the database is damaged. Data is recoverable only to the most recent backup of
the lost data. Therefore, under the simple recoverymodel, the backup intervals should be short enoughto prevent the loss of significant amounts of data.
Generally, the simple recovery model is useful onlyfor test and development databases or for databasescontaining mostly read-only data, such as a data
warehouse. The simple recovery model isinappropriate for production systems where loss ofrecent changes is unacceptable.
22
FullFull RecoveryRecovery andand BulkBulk--LoggedLogged RecoveryRecovery
These recovery models rely on backing up the transaction log toprovide full recoverability and to prevent work loss in the
broadest range of failure scenarios. Full recovery model:
Provides the normal database maintenance model fordatabases where durability of transactions is necessary.
This model fully logs all transactions and retains thetransaction log records until after they are backed up. Thefull recovery model allows a database to be recovered to thepoint of failure, assuming that the tail of the log can bebacked up after the failure. The full recovery model alsosupports restoring individual data pages.
23
BulkBulk--LoggedLogged RecoveryRecovery
This recovery model logs bulk operations in acompact way.
Log backups are still required.
Like the full recovery model, the bulk-logged recoverymodel retains transaction log records until after theyare backed up. The tradeoffs are bigger log backupsand increased work-loss exposure because the bulk-logged recovery model does not support point-in-timerecovery.
For certain large-scale bulk operations such as bulkimport or index creation, switching temporarily to the
bulk-logged recovery model increases performanceand reduces log space consumption
24
LogLog TruncationTruncation
If log records were never deleted from the transactionlog, the logical log would grow until it filled all theavailable space on the disks holding the physical log
files. To reduce the size of the logical log, it must betruncated periodically.
However, the active log can never truncated. Theactive log is required to recover the database. so itmust always be present in the database
Log truncation happens in multiple of virtual log files
8/14/2019 16-Transaction Management in SQL Server
7/24
25
LogLog TruncationTruncation
The recovery model selected for a databasedetermines how much of the transaction log in front
of the MinLSN must be retained in the database: Simple recovery model: all log records before the
MinLSN are truncated when a checkpoint isprocessed. The exception is if the checkpointoccurs when a BACKUP statement is still active.
Full or bulk-logged recovery models: after acheckpoint, the log remains intact until the nexttime that the transaction log is backed up.
Whether the truncation operation succeedsdepends on whether the active log has movedbeyond one or more virtual log files.
26
LogLog TruncationTruncation ExampleExample
After truncation
27
FactorsFactors thatthat PreventPrevent LogLog TruncationTruncation
A long-running active transaction is a transaction thathas started a long time ago and that has notcommitted nor aborted.
It prevents log truncation because it keeps a bigportion of the log active
28
BackupBackup
Backups allow you to restore data after a failure. Withproper backups, you can recover from many failures,including:
Hardware failures (such as a damaged disk drive).
User errors (such as dropping a table by mistake).
Natural disasters.
Additionally, backups of a database are useful forroutine administrative purposes, such as copying adatabase from one server to another
8/14/2019 16-Transaction Management in SQL Server
8/24
8/14/2019 16-Transaction Management in SQL Server
9/24
33
ExampleExample ofof DifferentialDifferential BackupsBackups
34
DifferentialDifferential BackupsBackups
Before restoring a differential backup, you mustrestore its differential base.
Typically you might take a weekly data backup of thedatabase (that is, a database backup) followed by aregular series of differential database backups duringthe week.
35
TypesTypes ofof DifferentialDifferential BackupsBackups
A differential database backup is based on adatabase backup.
A differential partial backup is based on a partial
backup.
A differential file backup is based on a file backup.
36
BackupBackup Under the Full andUnder the Full and BulkBulk--loggedlogged
RecoveryRecovery ModelsModels
Backups can be: data backups, differential backups,and, transaction log backups.
A data backup is the same as in the simple recovery
model A differential backup is the same as in the simple
recovery model
A transaction log backup (also called a logbackup) includes all log records not backed up in aprevious log backup. After the first data backup, youneed to begin backing up the transaction log on aregular basis.
8/14/2019 16-Transaction Management in SQL Server
10/24
37
ExampleExample ofof BackupBackup in the Full andin the Full and BulkBulk--
loggedlogged RecoveryRecovery ModelsModels
38
TypesTypes of Logof Log BackupsBackups
A log backup taken just before restoring a database to
capture log records that have not yet been backed up(the tail of the log). The tail-log backup is the last backupof interest in a recovery plan.
Tail-logbackup
A backup that includes log records as well as datapages changed by bulk operations. Point-in-timerecovery on bulk-logged backups is disallowed.
Bulk logbackup
A backup containing only transaction log records for aninterval
Pure logbackup
DescriptionBackup type
39
BulkBulk--loggedlogged RecoveryRecovery ModelModel
Bulk operations: CREATE INDEX, and bulk loading data(loading of a large number of rows from a file)
In contrast to the full recovery model, which fully logs all
transactions, the bulk-logged recovery model minimally logsbulk operations (though fully logging other transactions).
The bulk-logged recovery model protects against media failureand, for bulk operations, provides the best performance andleast log space usage.
However, the bulk-logged recovery model increases the risk ofdata loss for these bulk-copy operations because bulk-loggingoperations prevents recapturing changes on a transaction-by-transaction basis. A point-in-time restore is not possible. If a log
backup contains any bulk-logged operations, you can recoverthe database only to the end of the log backup.
40
Bulk LogBulk Log BackupBackup
A bulk log backup must capture both the log and theresults of every bulk-logged operation.
Therefore, it includes the data extents modified by
bulk operation.
The log backup operation relies on a bulk-changesbitmap page that contains a bit for every extent.For each extent updated by a bulk-logged operationsince the last log backup, the bit is set to 1 in thebitmap.
The data extents are copied into the log followed by
the log data.
8/14/2019 16-Transaction Management in SQL Server
11/24
41
Bulk LogBulk Log BackupBackup
42
RestoreRestore andand RecoveryRecovery
A consistent point of a database is one at which allparts of the database are at the same point in time
and no uncommitted transactions exist.
After a restore and before any portion of thedatabase can come back online, all data must berecovered to a consistent point (warm restart).
43
RestoringRestoring anan EntireEntire Database Under theDatabase Under the
SimpleSimple RecoveryRecovery Model (Model (ColdCold RestartRestart))
First restore a database backup
Then a differential backup (if it exists)
The database is offline for the duration of the restore
When the last backup is restored, the data must berecovered (warm restart) to bring the database into aconsistent state and bring it online
The database can be restored only to the point intime of the last backup. To this purpose, the logrecords stored in the backup are used
44
RestoringRestoring anan EntireEntire Database Under theDatabase Under the
SimpleSimple RecoveryRecovery ModelModel
If you are using only database backups, just restorethe most recent full database backup (WITHRECOVERY).
If you are using also differential database backups:
Restore the most recent database backup withoutrecovering the database (WITH NORECOVERY).
Restore the most recent differential databasebackup and recover the database (WITHRECOVERY).
8/14/2019 16-Transaction Management in SQL Server
12/24
45
ExampleExample
USE master;
--Ensure the database is using the simple recovery model:
ALTER DATABASE AdventureWorks SET RECOVERYSIMPLE;
GO
-- Create a logical backup device for the full AdventureWorksbackup.
EXEC sp_addumpdevice 'disk', 'MyAdvWorks_SimpleRM',
'C:\Program Files\Microsoft SQL
Server\MSSQL.1\MSSQL\BACKUP\MyAdvWorks_SimpleRM.bak';
GO
46
ExampleExample
-- Back up the full AdventureWorks database:
BACKUP DATABASE AdventureWorks TOMyAdvWorks_SimpleRM
WITH FORMAT;
GO
--Create a differential database backup:
BACKUP DATABASE AdventureWorks TOMyAdvWorks_SimpleRM
WITH DIFFERENTIAL;GO
47
ExampleExample
--Restore the full database backup (from backup set 1):
RESTORE DATABASE AdventureWorks FROMMyAdvWorks_SimpleRM
WITH NORECOVERY;
--Restore the differential backup (from backup set 2):
RESTORE DATABASE AdventureWorks FROMMyAdvWorks_SimpleRM
WITH FILE=2, RECOVERY;
GO
48
RestoringRestoring anan EntireEntire Database Under the FullDatabase Under the Full
RecoveryRecovery Model (Model (ColdCold RestartRestart))
In a complete database restore, the goal is to restorethe entire database to a specific point in time. Thepoint in time can be the point of failure, the most
recently available backup, a specific date and time, amarked transaction or a specifi LSN.
The database is offline for the duration of the restore.Before any portion of the database can come online,all data must be recovered to a consistent point.
8/14/2019 16-Transaction Management in SQL Server
13/24
49
RecoveringRecovering a Databasea Database toto thethe PointPoint ofof
FailureFailure
1. Back up the active transaction log (known as the tailof the log). This creates a tail-log backup. If the
active transaction log is unavailable, all transactionsin that portion of the log are lost.
2. Restore the most recent full database backupwithout recovering the database (WITHNORECOVERY).
3. If differential backups exist, restore the most recentone without recovering the database (WITH
NORECOVERY).
50
RecoveringRecovering a Databasea Database toto thethe PointPoint ofof
FailureFailure
4. Starting with the first transaction log backup createdafter the backup you just restored, restore the logs in
sequence with NORECOVERY.
This operation applies again the operationslogged in the log (roll forward phase)
5. Recover the database (RESTORE DATABASEWITH RECOVERY).Alternatively, this step can be combined withrestoring the last log backup.
This operations performs a warm restart
51
RecoveringRecovering a Databasea Database toto thethe PointPoint ofof
FailureFailure
Thus, the portion of the log necessary for performingrecovery (warm restart) is taken from backup, even ifthe log was not affected by the failure
That portion is the one contained in the backup of thetail of the log
52
ExampleExample
USE master;
GO
ALTER DATABASE AdventureWorks SET RECOVERY
FULL;GO
-- Create a logical backup device for the fullAdventureWorks backup.
EXEC sp_addumpdevice 'disk', 'MyAdvWorks_FullRM',
'C:\Program Files\Microsoft SQLServer\MSSQL.1\MSSQL\BACKUP\MyAdvWorks_Fu
llRM.bak';GO
8/14/2019 16-Transaction Management in SQL Server
14/24
53
ExampleExample
-- Back up the full AdventureWorks database:
BACKUP DATABASE AdventureWorks
TO MyAdvWorks_FullRM WITH FORMAT;GO
--Create a pure log backup:
BACKUP LOG AdventureWorks TO MyAdvWorks_FullRM;
GO
--Create tail-log backup:
BACKUP LOG AdventureWorks TO MyAdvWorks_FullRM
WITH NORECOVERY;
GO
54
ExampleExample
--Restore the full database backup (from backup set 1):
RESTORE DATABASE AdventureWorks FROM
MyAdvWorks_FullRM WITH NORECOVERY;--Restore the pure log backup (from backup set 2):
RESTORE LOG AdventureWorks FROM MyAdvWorks_FullRMWITH FILE=2, NORECOVERY;
--restore the tail-log backup (from backup set 3):
RESTORE LOG AdventureWorks FROM MyAdvWorks_FullRMWITH FILE=3, NORECOVERY;
GO
--recover the database:RESTORE DATABASE AdventureWorks WITH RECOVERY;
GO
55
RecoveringRecovering a Databasea Database toto aa PointPoint in Timein Time
The point in time is specified using one of thefollowing:
A specific time within a transaction log.
A named mark that was previously inserted intothe log.
A log sequence number (LSN).
56
SpecificSpecific TimeTime
RESTORE { DATABASE | LOG } FROMWITH STOPAT =
The recovery point is the latest transaction commit that occurredat or before the given
To restore only the modifications before a specific point in time: Restore the last full database backup and, if any, the last
differential database backup, without recovering thedatabase (WITH STOPAT= , NORECOVERY).
Apply each transaction log backup in the same sequence inwhich they were created, specifying the time at which youintend to stop restoring log (WITH STOPAT= ,NORECOVERY).
Recover the database to the desired point in time within atransaction log backup (WITH STOPAT=,RECOVERY).
8/14/2019 16-Transaction Management in SQL Server
15/24
57
NamedNamed MarkMark
To insert marks into the transaction logs, use theBEGIN TRANSACTION nameWITH MARK
[description] clause. The optional descriptionis atextual description of the mark.
The transaction log records the mark name,description, database, user, datetime information,and the log sequence number (LSN).
The datetime information is used along with the markname to uniquely identify the mark.
58
NamedNamed MarkMark
Use the WITH STOPATMARK = 'mark_name' [AFTER datetime] clause, which specifies that the
transaction withmark_nameafter datetimeis therecovery point.
STOPATMARK includes the marked transaction inthe roll forward.
59
LogLog SequenceSequence NumberNumber
You can stop at or immediately before the LSN, asfollows:
Use the WITH STOPATMARK = 'lsn:'
clause, where lsn:is a string thatspecifies that the log record containing the specifiedLSN is the recovery point.
STOPATMARK roll forwards to the LSN and includesthat log record in the roll forward.
60
OnlineOnline RestoreRestore
A file can be online or offline
A filegroup is online if all of its files are online,otherwise is offline
A database is online if its primary filegroup is online.Some or all of its secondary filegroups, if any, can beoffline.
Restoring a database puts it offline
After recovery, it is put back online
You can restore and recover offline files while adatabase is online. You also can restore one or morepages of an offline file while the database is online.(online restore).
8/14/2019 16-Transaction Management in SQL Server
16/24
61
LogLog BackupBackup
Minimally, you must have at least one full databasebackup, or an equivalent set of file backups, before
you can make any log backups.
A database administrator typically creates a fulldatabase backup at a periodic interval, such asweekly; optionally, creates a differential backup at ashorter interval, such as daily; and creates atransaction log backup quite frequently, such asevery 10 minutes.
62
LogLog BackupBackup
If your transaction log is damaged, you lose workperformed since the most recent log backup. This
suggests frequent log backups for critical data, andhighlights the importance of placing the log files onfault-tolerant storage.
The sequence of transaction log backups isindependent of the full database backups. You makeone sequence of transaction log backups, and thenmake periodic full database backups that are used to
start a restore operation.
63
ExampleExample
To restore the database to its state at 9:45 P.M. (thepoint of failure)
1. Create a tail-log backup of the currently activetransaction
Failure occurs.9:45 P.M.
Back up transaction log.8:00 P.M.
Back up database to create a full database backup.6:00 P.M.
Back up transaction log.4:00 P.M.
Back up transaction log.Noon
Back up database to create a full database backup.8:00 A.M.
EventTime
64
ExampleExample
2. Do not restore the 6:00 A.M. full database backup. Instead,restore the more recent 6:00 P.M. full database backup,
3. Apply the 8:00 P.M. log backup and the tail-log backup.
The restore process detects that the 8:00 P.M. transactionlog backup contains transactions that have occurred prior tothe last restored backup. The restore operation scans downthe transaction log to the point corresponding to when the6:00 P.M. full database backup completed. The restoreoperation then rolls forward only the completed transactionsfrom that point on within that transaction log backup.
This occurs again for the 9:45 P.M. transaction tail-logbackup.
8/14/2019 16-Transaction Management in SQL Server
17/24
65
ExampleExample
If a problem prevents you from using the 6:00 P.M.full database backup, then
1. Create a tail-log backup of the currently activetransaction log as of the point of failure.
2. Restore the 8:00 A.M. full database backup, andthen restore all four transaction log backups insequence. This rolls forward all completedtransactions up to 9:45 P.M.
This alternative points out the redundant securityoffered by maintaining a chain of transaction log
backups across a series of full database backups.
66
BackupBackup andand RestoreRestore in thein the BulkBulk--LoggedLogged
RecoveryRecovery ModelModel
The same as the full model, the only difference is thatif the log backup contains bulk-logged changes,
Point-in-time recovery is not allowed. Attempting touse point in time recovery displays an error and fail.
67
BackupBackup DevicesDevices
SQL Server identifies backup devices using either aphysical or logical device name:
A physical backup device is the name used by the
operating system to identify the backup device, forexample, C:\Backups\Accounting\Full.bak or
\\.\tape1.
A logical backup device is a user-defined alias, usedto identify the physical backup device. For example, alogical device name could be Accounting_Backup,but the physical device might be
E:\Backups\Accounting\Full.bak or \\.\tape1.
68
BackupBackup DevicesDevices
The stored procedure sp_addumpdevice adds alogical device to the instance, e.g.
-- Create logical backup device, AdvWorks_TestDev,
-- for disk file, C:\Backups\AdventureWorks_Full.Bak:
EXEC sp_addumpdevice 'disk', 'AdvWorks_TestDev',
'C:\AdventureWorks_Test.Bak'
8/14/2019 16-Transaction Management in SQL Server
18/24
69
ExampleExample
-- Either specify the logical backup device:
BACKUP DATABASE AdventureWorks
TO AdvWorks_TestDev-- Or, specify the physical backup device:
BACKUP DATABASE AdventureWorks
TO DISK = 'C:\AdventureWorks_Test.Bak'
-- Displaying the header information forAdvWorks_TestDev
-- lists both backups
RESTORE HEADERONLYFROM AdvWorks_TestDev
70
BackupBackup DevicesDevices
More than one backup device can be specified
The set of media used in one or more backups on
the same devices (one or more files, one or moretapes) is called a media set
The space reserved for a single backup on a mediaset is called a backup set
The first time a media set is used it must beformatted, i.e. a header must be written to the mediaset
Each backup set is preceded by a header
71
MultipleMultiple BackupBackup DevicesDevices
Multiple backup devices allows SQL Server to useparallel input/output (I/O) to increase the speed ofbackup and restore operations because each backup
device can be written to or read from at the sametime as other backup devices.
72
ExampleExample
BACKUP DATABASE AdventureWorks
TO TAPE = '\\.\tape0', TAPE = '\\.\tape1', TAPE ='\\.\tape2'
WITH
FORMAT,
MEDIANAME = 'MyAdvWorks_MediaSet_1'
This operations distributes the data on the threetapes. If the data does not fit on the three tapes,backup asks for the insertion of three new tapes.
The media set is the set of the three initial tapes plusany additional tape that is necessary
8/14/2019 16-Transaction Management in SQL Server
19/24
73
ExampleExample
74
BackupBackup inin AppendAppend
A backup set can be appended to a media set, e.g.
BACKUP DATABASE AdventureWorks
TO TAPE = '\\.\tape0', TAPE = '\\.\tape1', TAPE ='\\.\tape2'
WITH
MEDIANAME = 'Adventure_WorksMedia_Set1',
DIFFERENTIAL
75
ExampleExample
76
RestoreRestore of aof a BackupBackup SetSet
When a media set contains more than one backupset, the clause WITH FILE=file_numberspecifies thebackup set
For example, a file_numberof 1 indicates the firstbackup set on the media set and a file_numberof 2indicates the second backup set and so no
When not specified, the default is 1
8/14/2019 16-Transaction Management in SQL Server
20/24
8/14/2019 16-Transaction Management in SQL Server
21/24
81
OverwritingOverwriting
Overwriting a media set fails if
The existing backups on the media have not
expired. (If SKIP is specified, expiration is notchecked.)
The media name, if provided, does not match thename on the backup media.
82
MirroredMirrored Media SetMedia Set
Backup can be performed onmirrored media set for
improved reliability, e.gBACKUP DATABASE
AdventureWorks
TO TAPE = '\\.\tape0', TAPE ='\\.\tape1'
MIRROR TO TAPE = '\\.\tape2',TAPE = '\\.\tape3'
WITH
FORMAT,MEDIANAME ='AdventureWorksSet1'
83
ManagingManaging BackupBackup MediaMedia
A plan for overwriting backup media should beprepared (setting expiration times accordingly)
In the case in which we want to be able to recover
from a disaster (such as a fire or flood), the backupmedia (tapes) should be stored in a different locationthan the server machine,
However, restore time in non-disaster situations isincreased
Use mirrored copies and ship away only one copy
84
TransactionsTransactions
Explicit Transactions Explicitly start a transaction through an API function or by
issuing the Transact-SQL BEGIN TRANSACTIONstatement.
Autocommit Transactions The default mode for the Database Engine. Each individualTransact-SQL statement is committed when it completes.You do not have to specify any statements to controltransactions.
Implicit Transactions Set implicit transaction mode on through either an API
function or the Transact-SQL SETIMPLICIT_TRANSACTIONS ON statement. The nextstatement automatically starts a new transaction. When thattransaction is completed, the next Transact-SQL statement
starts a new transaction.
8/14/2019 16-Transaction Management in SQL Server
22/24
85
ExplicitExplicit TransactionsTransactions
BEGIN TRANSACTION
Marks the starting point of an explicit transaction
for a connection.
COMMIT TRANSACTION or COMMIT WORK
Used to end a transaction successfully if no errorswere encountered.
ROLLBACK TRANSACTION or ROLLBACK WORK
Used to erase a transaction in which errors areencountered.
86
ImplicitImplicit TransactionsTransactions
The instance of the Database Engine automaticallystarts a transaction when it first executes any
statement. The transaction remains in effect until you issue a
COMMIT or ROLLBACK statement.
After the first transaction is committed or rolled back,the instance of the Database Engine automaticallystarts a new transaction the next time any statementsis executed by the connection. The instance keeps
generating a chain of implicit transactions untilimplicit transaction mode is turned off.
87
IsolationIsolation LevelsLevels
SQL Server 2005 support all SQL-99 isolation levels
It also supports two transaction isolation levels thatuse row versioning.
A new implementation of read committed isolation
A new transaction isolation level, snapshot.
88
SnapshotSnapshot IsolationIsolation LevelLevel
The snapshot isolation level uses row versioning toprovide transaction-level read consistency.
Read operations acquire no page or row locks. When
reading rows modified by another transaction, theyretrieve the version of the row that existed when thetransaction started. Snapshot isolation is enabledwhen the ALLOW_SNAPSHOT_ISOLATIONdatabase option is set ON. By default, this option isset OFF for user databases.
8/14/2019 16-Transaction Management in SQL Server
23/24
89
SettingSetting thethe IsolationIsolation LevelLevel
Only one of the isolation level options can be set at atime, and it remains set for that connection until it is
explicitly changedSET TRANSACTION ISOLATION LEVEL
{ READ UNCOMMITTED
| READ COMMITTED
| REPEATABLE READ
| SNAPSHOT
| SERIALIZABLE } [ ; ]
90
READ COMMITTEDREAD COMMITTED
Specifies that statements cannot read data that hasbeen modified but not committed by other
transactions. This prevents dirty reads. Data can be changed by other transactions between
individual statements within the current transaction,resulting in nonrepeatable reads or phantom inserts.This option is the SQL Server default.
91
READ COMMITTEDREAD COMMITTED
The behavior of READ COMMITTED depends on the setting ofthe READ_COMMITTED_SNAPSHOT database option:
If READ_COMMITTED_SNAPSHOT is set to OFF (thedefault), the Database Engine uses shared locks to prevent
other transactions from modifying rows while the currenttransaction is running a read operation.
If READ_COMMITTED_SNAPSHOT is set to ON, theDatabase Engine uses row versioning to present eachstatement with a transactionally consistent snapshot of thedata as it existed at the start of the statement. Locks are notused to protect the data from updates by other transactions.
92
SNAPSHOTSNAPSHOT
Specifies that data read by any statement in atransaction will be the transactionally consistentversion of the data that existed at the start of thetransaction.
The transaction can only recognize datamodifications that were committed before the start ofthe transaction.
Data modifications made by other transactions afterthe start of the current transaction are not visible tostatements executing in the current transaction.
The effect is as if the statements in a transaction get
a snapshot of the committed data as it existed at thestart of the transaction.
8/14/2019 16-Transaction Management in SQL Server
24/24
93
SNAPSHOTSNAPSHOT
SNAPSHOT transactions do not request locks whenreading data.
SNAPSHOT transactions reading data do not blockother transactions from writing data.
Transactions writing data do not block SNAPSHOTtransactions from reading data.
SNAPSHOT avoids all the anomalies, as theSERIALIZABLE isolation level
94
ChangingChanging IsolationIsolation LevelLevel
You can switch from one isolation level to another atany time during a transaction
Exception: changing from any isolation level toSNAPSHOT isolation causes the transaction to failand roll back.
However, you can change a transaction started inSNAPSHOT isolation to any other isolation level.
95
ChangingChanging IsolationIsolation LevelLevel
When you change a transaction from one isolationlevel to another, resources read after the change areprotected according to the rules of the new level.
Resources read before the change continue to beprotected according to the rules of the previous level.
For example, if a transaction changed from READCOMMITTED to SERIALIZABLE, the shared locksacquired after the change are now held until the endof the transaction.
96
ExampleExample
USE AdventureWorks;GOALTER DATABASE AdventureWorks SET
READ_COMMITTED_SNAPSHOT ON;SET TRANSACTION ISOLATION LEVEL READ COMMITTED;GOBEGIN TRANSACTION;GO
SELECT *FROM HumanResources.EmployeePayHistory;
GOSELECT *
FROM HumanResources.Department;GOCOMMIT TRANSACTION;GO