Log in SQL Server Transaction Management in in SQL Server 2005 The log (or transaction log) is implemented as a separate file or set of files in the database. The log cache is managed separately from the buffer cache for data pages The format of log records and pages is not constrained to follow the format of data pages. The transaction log can be implemented in several files. The files can be defined to expand automatically by setting the FILEGROWTH value for the log. 2 Use of the Log at Startup When SQL Server is started, the log is used to perform a warm restart (or recovery) This is done in case the SQL Server process was stopped by a failure Log Logical Architecture Each log record is identified by a log sequence number (LSN). Each new log record is written to the logical 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 transaction that it belongs to. For each transaction, all log records associated with the transaction are individually linked in a chain using backward pointers that speed the rollback of the transaction. 3 4
Operations 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 by system stored procedures or data definition language (DDL) statements. Every extent and page allocation or deallocation. Creating or dropping a table or index. MinLSN,, Active Log The Minimum Recovery LSN (MinLSN) is the LSN of the first log record that must be present for a successful recovery. MinLSN is the minimum of the: LSN of the start of the last checkpoint LSN of the start of the oldest transaction in the UNDO and REDO sets of the last checkpoint The part of the log from MinLSN to the last record is called the active log This is the section of the log required to do a recovery of the database. No part of the active log can ever be truncated. 5 6 MinLSN At the time that the recorded checkpoint at LSN 147 was processed, Tran 1 had been committed and Tran 2 was the only active transaction. That makes B(Tran2) the start of the oldest transaction 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. 7 Checkpoint A checkpoint performs the following processes: Writes a record to the log file marking the start of the checkpoint. Stores information recorded for the checkpoint in a chain of checkpoint log records. One piece of information is the MinLSN. Another piece of information is a list of all the active transactions that have modified the database. Writes all dirty log and data pages of committed transactions to disk. Writes a record marking the end of the checkpoint to the log file. Writes the LSN of the start of this chain to the database boot page 8
Checkpoint Checkpoints occur for example in the following situations: A CHECKPOINT statement is explicitly executed. A minimally logged operation is performed in the database; for example, a bulk-copy operation is performed on a database that is using the Bulk-Logged recovery model. Database files have been added or removed by using ALTER DATABASE. An instance of SQL Server is stopped by a SHUTDOWN statement or by stopping the SQL Server (MSSQLSERVER) service. Either will checkpoint each database in the instance of SQL Server. An instance of SQL Server periodically generates automatic checkpoints in each database to reduce the time that the instance would take to recover the database. A database backup is taken. Automatic Checkpoints The interval between automatic checkpoints is based on the amount of log space used and the time elapsed since the last checkpoint. This interval can be highly variable. It is long if few modifications are made in the database, otherwise it is short. This interval is calculated for all the databases on a server instance from the recovery interval server configuration option. This option specifies the maximum time SQL Server should use to recover a database during a system restart. SQL Server estimates how many log records it can process in the recovery interval during a recovery operation. 9 10 Virtual Log Files Conceptually, the log file is a string of log records. Physically, the sequence of log records is stored efficiently in the set of physical files SQL Server divides each physical log file internally into a number of virtual log files. They are the unit of space that can be reused Virtual log files have no fixed size, and there is no fixed number of virtual log files for a physical log file. SQL Server chooses the size of the virtual log files dynamically while it is creating or extending log files. SQL Server tries to maintain a small number of virtual files. Virtual Log Files Virtual log files can affect system performance if the log files are defined by small size and growth_increment values. If these log files grow to a large size because of many small increments, they will have lots of virtual log files. This can slow down database startup and also log backup and restore operations. One should assign log files a size value close to the final size required, and also have a relatively large growth_increment value 11 12
Log When the database is created, the logical log file begins at the start of the physical log file. New log records are added at the end of the logical log and expand toward the end of the physical log. Log records in the virtual logs that appear in front of MinLSN are deleted with a truncation operation. Log The transaction log is a wrap-around file: when the end of the logical log reaches the end of the physical log file, the new log records wrap around to the start of the physical log file. 13 14 Log This cycle repeats endlessly, as long as the end of the logical log never reaches the beginning of the logical log. If the old log records are truncated frequently enough to always leave sufficient room for all the new log records created from the last checkpoint, the log never fills. If the log contains multiple physical log files, the logical log will move through all the physical log files before it wraps back to the start of the first physical log file. Log If the end of the logical log does reach the start of the logical log, one of two things occurs: If the FILEGROWTH setting is enabled for the log and space is available on the disk, the file is extended by the amount specified in growth_increment and the new log records are added to the extension. If the FILEGROWTH setting is not enabled, or the disk that is holding the log file has less free space than the amount specified in growth_increment, an 9002 error is generated. 15 16
Recovery Models Recovery Models Recovery model Description Work loss exposure Recovery Recovery model Description Work loss exposure Recovery Simple No log backups. Automatically reclaims log space to keep space requirements small, essentially eliminating the need to manage the transaction log space. Changes since the most recent backup are unprotected. In the event of a disaster, those changes need to be redone. Can recover only to the end of a data backup. Full Requires log backups. No work is lost due to a lost or damaged data file. Normally none. If the tail of the log is damaged, changes since the most recent log backup must be redone. Can recover to a specific point in time (for example, prior to application or user error), assuming that your backups are complete up to that point in time. 17 18 Recovery Models Simple Recovery Model Recovery model Bulk logged Description Requires log backups. An adjunct of the full recovery model that permits highperformance bulk copy operations. Reduces log space usage by bulk logging most bulk operations. Work loss exposure If the log is damaged or bulklogged operations occurred since the most recent log backup, changes since that last log backup must be redone. Otherwise, no work is lost. Recovery Can recover to the end of any backup. Point-in-time recovery is not supported. At the next automatic checkpoint, the log space is automatically truncated to free log space for reuse, even if it was not backed up Because the transaction log is not backed up, the simple recovery model risks significant work-loss exposure if the database is damaged. 19 20
Simple Recovery Model Data is recoverable only to the most recent backup of the lost data. Therefore, under the simple recovery model, the backup intervals should be short enough to prevent the loss of significant amounts of data. Generally, the simple recovery model is useful only for test and development databases or for databases containing mostly read-only data, such as a data warehouse. The simple recovery model is inappropriate for production systems where loss of recent changes is unacceptable. Full Recovery and Bulk-Logged Recovery These recovery models rely on backing up the transaction log to provide full recoverability and to prevent work loss in the broadest range of failure scenarios. Full recovery model: It provides the normal database maintenance model for databases where durability of transactions is necessary. It fully logs all transactions and retains the transaction log records until after they are backed up. It allows a database to be recovered to the point of failure, assuming that the tail of the log can be backed up after the failure. 21 22 Bulk-Logged Recovery It logs bulk operations in a compact way. Log backups are still required. It retains transaction log records until after they are backed up. It does not support point-in-time recovery. For certain large-scale bulk operations such as bulk import or index creation, switching temporarily to the bulk-logged recovery model increases performance and reduces log space consumption Log Truncation If log records were never deleted from the transaction log, the logical log would grow until it filled all the available space on the disks holding the physical log files. To reduce the size of the logical log, it must be truncated periodically. Log truncation happens in multiple of virtual log files 23 24
Log Truncation The recovery model selected for a database determines 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 is processed. Full or bulk-logged recovery models: after a checkpoint, the log remains intact until the next time that the transaction log is backed up. If the active log has moved beyond one or more virtual log files, then truncation is performed. After truncation Log Truncation 25 26 Factors that Prevent Log Truncation A long-running active transaction is a transaction that has started a long time ago and that has not committed nor aborted. It prevents log truncation because it keeps a big portion of the log active Backup Backups allow you to restore data after a failure. With proper backups, you can recover from many failures, including: Software failures (bugs in the Server or in the Operating System) Power failures 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 for administrative purposes, such as copying a database from one server to another 27 28
Backup Backups are created on backup devices, such as disk or tape. During a backup, SQL Server copies the data directly from the database files to the backup devices. The data is not changed, and transactions running during the backup are never delayed. Backup Under the Simple Recovery Model Backups can be: data backups and differential backups. A data backup is any backup that includes the entire image of one or more data files or filegroups. SQL Server supports data backups of the following: All of the filegroups in a database (a database backup) Any combination of files/filegroups (a file backup). A data backup covers all the data in the backed up data files plus enough log to permit recovering that data. 29 30 of a database backup in the Simple Recovery Model Differential Backup A differential backup is based on the most recent data backup of the data files covered by the differential backup. The data backup on which a differential backup is based is known as the differential base. A differential backup contains only data extents that have changed since the differential base was created plus enough log to permit recovering that data The size of a differential backup increases as the time from the last data backup increases 31 32
of Differential Backups Differential Backups Before restoring a differential backup, you must restore its differential base. Typically you might take a weekly data backup of the database (that is, a database backup) followed by a regular series of differential database backups during the week. 33 34 Types of Differential Backups A differential database backup is based on a database backup. A differential file backup is based on a file backup. Backup Under the Full and Bulk-logged logged Recovery Models 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 log backup) includes all log records not backed up in a previous log backup. After the first data backup, you need to begin backing up the transaction log on a regular basis. 35 36
of Backup in the Full and Bulk- logged Recovery Models Types of Log Backups Backup type Pure log backup Bulk log backup Tail-log backup Description A backup containing only transaction log records for an interval A backup that includes log records as well as data pages changed by bulk operations. Point-in-time recovery on bulk-logged backups is disallowed. 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 backup of interest in a recovery plan. 37 38 Bulk-logged logged Recovery Model 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 logs bulk operations (though fully logging other transactions). The bulk-logged recovery model protects against media failure and, for bulk operations, provides the best performance and least log space usage. However, the bulk-logged recovery model increases the risk of data loss for these bulk-copy operations because bulk-logging operations prevents recapturing changes on a transaction-bytransaction basis. A point-in-time restore is not possible. If a log backup contains any bulk-logged operations, you can recover the database only to the end of the log backup. Bulk Log Backup A bulk log backup must capture both the log and the results of every bulk-logged operation. Therefore, it includes the data extents modified by bulk operation. The log backup operation relies on a bulk-changes bitmap page that contains a bit for every extent. For each extent updated by a bulk-logged operation since the last log backup, the bit is set to 1 in the bitmap. The data extents are copied into the log followed by the log data. 39 40
Bulk Log Backup Restore and Recovery A consistent point of a database is one at which all parts of the database are at the same point in time and no uncommitted transactions exist. After a restore and before any portion of the database can come back online, all data must be recovered to a consistent point (warm restart). Recovery is always performed from a backup, never from the files, even if these are available: Before performing recovery using the active portion of the log, this must be backed up with a tail log backup operation 41 42 Restoring an Entire Database Under the Simple Recovery Model (Cold( Restart) 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 be recovered (warm restart) to bring the database into a consistent state and bring it online The database can be restored only to the point in time of the last backup. To this purpose, the log records stored in the backup are used Restoring an Entire Database Under the Simple Recovery Model If you are using only database backups, just restore the most recent full database backup (WITH RECOVERY). If you are using also differential database backups: Restore the most recent database backup without recovering the database (WITH NORECOVERY). Restore the most recent differential database backup and recover the database (WITH RECOVERY). 43 44
USE master; --Ensure the database is using the simple recovery model: ALTER DATABASE AdventureWorks SET RECOVERY SIMPLE; -- Create a logical backup device for the full AdventureWorks backup. EXEC sp_addumpdevice 'disk', 'MyAdvWorks_SimpleRM', 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\BACKUP\MyAdvWorks_Simple RM.bak'; -- Back up the full AdventureWorks database: BACKUP DATABASE AdventureWorks TO MyAdvWorks_SimpleRM WITH FORMAT; --Create a differential database backup: BACKUP DATABASE AdventureWorks TO MyAdvWorks_SimpleRM WITH DIFFERENTIAL; 45 46 --Restore the full database backup (from backup set 1): RESTORE DATABASE AdventureWorks FROM MyAdvWorks_SimpleRM WITH NORECOVERY; --Restore the differential backup (from backup set 2): RESTORE DATABASE AdventureWorks FROM MyAdvWorks_SimpleRM WITH FILE=2, RECOVERY; Restoring an Entire Database Under the Full Recovery Model (Cold( Restart) In a complete database restore, the goal is to restore the entire database to a specific point in time. The point in time can be the point of failure, the most recently available backup, a specific date and time, a marked transaction or a specific 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. 47 48
Recovering a Database to the Point of Failure 1. Back up the portion of the log not yet backed up (known as the tail of the log). This creates a tail-log backup. If the transaction log is unavailable, all transactions after the last log backup are lost. 2. Restore the most recent full database backup without recovering the database (WITH NORECOVERY). 3. If differential backups exist, restore the most recent one without recovering the database (WITH NORECOVERY). Recovering a Database to the Point of Failure 4. Starting with the first transaction log backup created after the backup you just restored, restore the logs in sequence with NORECOVERY. This operation applies again the operations logged in the log (roll forward phase) 5. Recover the database (RESTORE DATABASE <database_name> WITH RECOVERY). Alternatively, this step can be combined with restoring the last log backup. This operations performs a warm restart 49 50 Recovering a Database to the Point of Failure Thus, the portion of the log necessary for performing recovery (warm restart) is taken from backup, even if the log was not affected by the failure That portion is the one contained in the backup of the tail of the log 51 USE master; ALTER DATABASE AdventureWorks SET RECOVERY FULL; -- Create a logical backup device for the full AdventureWorks backup. EXEC sp_addumpdevice 'disk', 'MyAdvWorks_FullRM', 'C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\BACKUP\MyAdvWorks_Fu llrm.bak'; 52
-- Back up the full AdventureWorks database: BACKUP DATABASE AdventureWorks TO MyAdvWorks_FullRM WITH FORMAT; --Create a pure log backup: BACKUP LOG AdventureWorks TO MyAdvWorks_FullRM; --Create tail-log backup: BACKUP LOG AdventureWorks TO MyAdvWorks_FullRM WITH NORECOVERY; --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_FullRM WITH FILE=2, NORECOVERY; --restore the tail-log backup (from backup set 3): RESTORE LOG AdventureWorks FROM MyAdvWorks_FullRM WITH FILE=3, NORECOVERY; --recover the database: RESTORE DATABASE AdventureWorks WITH RECOVERY; 53 54 Recovering a Database to a Point in Time The point in time is specified using one of the following: A specific time within a transaction log. A named mark that was previously inserted into the log. A log sequence number (LSN). Online Restore 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 be offline. Restoring a database puts it offline After recovery, it is put back online You can restore and recover offline files while a database is online. 55 56
Log Backup If your transaction log is damaged, you lose work performed since the most recent log backup. This suggests frequent log backups for critical data, for example every 10 minutes, and highlights the importance of placing the log files on fault-tolerant storage. The sequence of transaction log backups is independent of the full database backups. You make one sequence of transaction log backups, and then make periodic full database backups that are used to start a restore operation. Noon Time 8:00 A.M. 4:00 P.M. 6:00 P.M. 8:00 P.M. 9:45 P.M. Failure occurs. Back up transaction log. Back up transaction log. Back up database to create a full database backup. Back up transaction log. Event Back up database to create a full database backup. To restore the database to its state at 9:45 P.M. (the point of failure) 1. Create a tail-log backup 57 58 2. Do not restore the 8: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. transaction log backup contains transactions that have occurred prior to the last restored backup. The restore operation scans down the transaction log to the point corresponding to when the 6:00 P.M. full database backup completed. The restore operation then rolls forward from that point on within that transaction log backup. This occurs again for the 9:45 P.M. transaction tail-log backup. 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 active transaction log as of the point of failure. 2. Restore the 8:00 A.M. full database backup, and then restore all four transaction log backups in sequence. This rolls forward all completed transactions up to 9:45 P.M. This alternative points out the redundant security offered by maintaining a chain of transaction log backups across a series of full database backups. 59 60
Backup and Restore in the Bulk-Logged Recovery Model The same as the full model, the only difference is that if the log backup contains bulk-logged changes, point-in-time recovery is not allowed. Backup Devices SQL Server identifies backup devices using either a physical or logical device name: A physical backup device is the name used by the operating system to identify the backup device, for example, C:\Backups\Accounting\Full.bak or \\.\tape1. A logical backup device is a user-defined alias, used to identify the physical backup device. For example, a logical device name could be Accounting_Backup, but the physical device might be E:\Backups\Accounting\Full.bak or \\.\tape1. 61 62 Backup Devices The stored procedure sp_addumpdevice adds a logical 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' -- 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 for -- AdvWorks_TestDev lists both backups RESTORE HEADERONLY FROM AdvWorks_TestDev 63 64
Backup Devices 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 more tapes) is called a media set The space reserved for a single backup on a media set is called a backup set The first time a media set is used it must be formatted, i.e. a header must be written to the media set Each backup set is preceded by a header Multiple Backup Devices Multiple backup devices allows SQL Server to use parallel input/output (I/O) to increase the speed of backup and restore operations because each backup device can be written to or read from at the same time as other backup devices. 65 66 BACKUP DATABASE AdventureWorks TO TAPE = '\\.\tape0', TAPE = '\\.\tape1', TAPE = '\\.\tape2' WITH FORMAT, MEDIANAME = 'AdventureWorksMediaSet1' This operations distributes the data on the three tapes. 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 plus any additional tape that is necessary 67 68
Backup in Append A backup set can be appended to a media set, e.g. BACKUP DATABASE AdventureWorks TO TAPE = '\\.\tape0', TAPE = '\\.\tape1', TAPE = '\\.\tape2' WITH MEDIANAME = 'AdventureWorksMediaSet1', DIFFERENTIAL 69 70 Restore of a Backup Set When a media set contains more than one backup set, the clause WITH FILE=file_number specifies the backup set For example, a file_number of 1 indicates the first backup set on the media set and a file_number of 2 indicates the second backup set and so no When not specified, the default is 1 RESTORE DATABASE AdventureWorks FROM TAPE = '\\.\tape0', TAPE = '\\.\tape1', TAPE = '\\.\tape2' WITH MEDIANAME = 'AdventureWorksMediaSet1', FILE=1, NORECOVERY; RESTORE DATABASE AdventureWorks FROM TAPE = '\\.\tape0', TAPE = '\\.\tape1', TAPE = '\\.\tape2' WITH MEDIANAME = 'AdventureWorksMediaSet1', FILE=2, RECOVERY; 71 72
Expiration date When you create a backup you can specify an expiration date The expiration date is a date after which the backup can be deleted or overwritten. Backup on an Existing Media Set Three alternatives: Append (already seen) Overwrite: deletes the existing backup sets but keeps the media set header. Use the INIT option of the BACKUP statement. Useful if we do not want to change the media set name Format: deletes the existing backup sets and replaces the media set header with a new one. Use the FORMAT option of the BACKUP statement 73 74 Overwriting Overwriting a media set fails if The existing backups on the media have not expired. (If SKIP is specified, expiration is not checked.) The media name, if provided, does not match the name on the backup media. Backup can be performed on mirrored media set for improved reliability, e.g BACKUP DATABASE AdventureWorks TO TAPE = '\\.\tape0', TAPE = '\\.\tape1' MIRROR TO TAPE = '\\.\tape2', TAPE = '\\.\tape3' WITH FORMAT, MEDIANAME = 'AdventureWorksSet1' Mirrored Media Set 75 76
Managing Backup Media A plan for overwriting backup media should be prepared (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 backup media (tapes) should be stored in a different location than the server machine, However, restore time in non-disaster situations is increased Use mirrored copies and ship away only one copy Transactions Explicit Transactions Explicitly start a transaction through an API function or by issuing the Transact-SQL BEGIN TRANSACTION statement. Autocommit Transactions The default mode for SQL Server. Each individual Transact- SQL statement is committed when it completes. You do not have to specify any statements to control transactions. Implicit Transactions Set implicit transaction mode on through either an API function or the Transact-SQL SET IMPLICIT_TRANSACTIONS ON statement. The next statement automatically starts a new transaction. When that transaction is completed with COMMIT or ROLLBACK, the next Transact-SQL statement starts a new transaction. 77 78 Explicit Transactions 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 errors were encountered. ROLLBACK [TRANSACTION] or ROLLBACK [WORK] Used to erase a transaction in which errors are encountered. Implicit Transactions SQL Server automatically starts 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, SQL Server automatically starts a new transaction the next time any statements is executed by the connection. SQL Server keeps generating a chain of implicit transactions until implicit transaction mode is turned off. 79 80
Isolation Levels SQL Server 2005 support all SQL-99 isolation levels It also supports two transaction isolation levels that use row versioning. A new implementation of read committed isolation A new transaction isolation level, snapshot. Snapshot Isolation Level The snapshot isolation level uses row versioning to provide transaction-level read consistency. Read operations acquire no page or row locks. When reading rows modified by another transaction, they retrieve the version of the row that existed when the transaction started. Snapshot isolation is enabled when the ALLOW_SNAPSHOT_ISOLATION database option is set ON. By default, this option is set OFF for user databases. 81 82 Setting the Isolation Level Only one of the isolation level options can be set at a time, and it remains set for that connection until it is explicitly changed SET TRANSACTION ISOLATION LEVEL { READ UNCOMMITTED READ COMMITTED REPEATABLE READ SNAPSHOT SERIALIZABLE } [ ; ] READ COMMITTED Specifies that statements cannot read data that has been 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, ghost updates or phantom inserts. This option is the SQL Server default. Deafult level for SQL Server 83 84
READ COMMITTED The behavior of READ COMMITTED depends on the setting of the READ_COMMITTED_SNAPSHOT database option: If READ_COMMITTED_SNAPSHOT is set to OFF (the default), SQL Server uses shared locks to implement READ COMMITTED. If READ_COMMITTED_SNAPSHOT is set to ON, SQL Server uses row versioning to to implement READ COMMITTED. Locks are not used to protect the data from updates by other transactions. 85 SNAPSHOT Specifies that data read by any statement in a transaction will be the transactionally consistent version of the data that existed at the start of the transaction. The transaction can only recognize data modifications that were committed before the start of the transaction. Data modifications made by other transactions after the start of the current transaction are not visible to statements 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 the start of the transaction. 86 SNAPSHOT SNAPSHOT transactions do not request locks when reading data. SNAPSHOT transactions reading data do not block other transactions from writing data. Transactions writing data do not block SNAPSHOT transactions from reading data. SNAPSHOT avoids all the anomalies, as the SERIALIZABLE isolation level Changing Isolation Level You can switch from one isolation level to another at any time during a transaction Exception: changing from any isolation level to SNAPSHOT isolation causes the transaction to fail and roll back. However, you can change a transaction started in SNAPSHOT isolation to any other isolation level. 87 88
Changing Isolation Level When you change a transaction from one isolation level to another, resources read after the change are protected according to the rules of the new level. Resources read before the change continue to be protected according to the rules of the previous level. For example, if a transaction changed from READ COMMITTED to SERIALIZABLE, the shared locks acquired after the change are now held until the end of the transaction. USE AdventureWorks; ALTER DATABASE AdventureWorks SET READ_COMMITTED_SNAPSHOT ON; SET TRANSACTION ISOLATION LEVEL READ COMMITTED; BEGIN TRANSACTION; SELECT * FROM HumanResources.EmployeePayHistory; SELECT * FROM HumanResources.Department; COMMIT TRANSACTION; 89 90