CHAPTER 31 Transaction Management and the Transaction Log when the database is in simple recovery mode, or when you have never performed a full backup of the database.. This view, which
Trang 1CHAPTER 31 Transaction Management and the Transaction Log
when the database is in simple recovery mode, or when you have never performed a full
backup of the database
If the database is configured to use the bulk-logged or full recovery models so that the log
is being maintained, the reusable portion of the log prior to the MinLSN cannot be
trun-cated or purged until the transaction log has actually been backed up
If the first VLF cannot be reused because it contains the MinLSN or it hasn’t been
trun-cated yet, SQL Server needs to expand the log file This is done by adding a new VLF to
the end of the physical log (as long as the log file is still configured to grow
automati-cally) SQL Server can then continue writing log records to the new VLF However, if the
log file is not configured to auto-grow, a 9002 error is generated, indicating that the log
file is out of space
Certain conditions can cause log records to remain active, preventing the MinLSN from
moving out of the first VLF, which in turn prevents the VLFs at the beginning of the
phys-ical log file from being reused Some of the conditions that can lead to the log space not
being reused include, but are not limited to, the following:
records are needed for database recovery
Mirroring.”)
relevant to the publications have not yet been delivered to the distribution database
(For more information on replication, see Chapter 19, “Replication.”)
“Database Snapshots”)
If something is preventing the log from being truncated, SQL Server 2008 provides
mation in the system catalogs to determine what is preventing log truncation This
view, which you can display by using a query similar to the following:
select name, log_reuse_wait_desc
from sys.databases
where name = db_name()
When a log file is configured to auto-grow and there is significant update activity against
the database and the inactive portion of the transaction log is not being truncated
frequently enough (or at all) to allow for the reuse of VLFs, the log file size can become
excessive This can lead to insufficient disk space in the file system that contains the log
Trang 2file This can subsequently also lead to a 9002 out-of-space error if the log file needs to
grow and not enough disk space is available At times, you might need to shrink the log
file to reduce its size
Shrinking the Log File
After the log has been backed up and the active portion of the log has wrapped around to
the beginning of the log file, the VLFs at the end of the physical log can be deleted from
the log file, and the log file can be reduced in size
When you shrink a log file, the space freed can only come from the end of the log file
The unit of size reduction is the size of the virtual log file For example, if you have a 1GB
log file that has been divided into five 200MB virtual log files, the log file can only be
shrunk in 200MB increments The file size can be reduced to sizes such as 800MB or
400MB, but the file cannot be reduced to sizes such as 333MB or 750MB
log file Its syntax is as follows:
DBCC SHRINKFILE ( { ’file_name’ } { [,EMPTYFILE] | [,target_size ] } )
[ WITH NO_INFOMSGS ]
many of the inactive virtual log files from the end of the physical log file as possible to
restore the transaction log file to its default size The default size of the transaction log file
DATABASE command
VLFs from the end of the log file as possible to reduce the log file to as close to the target
size as possible without making the log smaller than the specified target size After
shrink-ing, the log file is typically somewhat larger than the target size, especially if the target
size is not a multiple of the VLF size
mark does contain an active portion of the log, SQL Server frees from the end of the
phys-ical log file as many of the VLFs as possible that do not contain active portions of the log
indi-cating that not all the requested space was freed When the active portion of the log
SHRINK-FILE statement again to free the remaining space
You can also use SQL Server Management Studio (SSMS) to shrink the transaction log file
Trang 3ptg CHAPTER 31 Transaction Management and the Transaction Log
In the File Type drop-down list, select Log To shrink the log file to its default size, click
the radio button next to Release Unused Space in the Shrink Action area of the dialog box
To shrink the log file to a desired size, click the radio button next to Reorganize Pages
Before Releasing Unused Space and specify the desired target size After you choose the
desired shrink option, click OK
In addition to manually shrinking the transaction log, SQL Server also provides a database
automati-cally when space is available at the end of the file If you are regularly backing up or
auto-shrink process runs periodically and determines whether the log file can be shrunk
The Log Manager keeps track of how much log space has been used since the auto-shrink
process last ran The auto-shrink process then shrinks the log either to 125% of the
maximum log space used since auto-shrink last ran or the default size of the transaction
log file, whichever is larger
Trang 4TIP
Repeated growing and shrinking of the log file can lead to excessive file fragmentation,
which can have an adverse impact on the file I/O performance It is recommended that
grow to during normal processing and enable the auto-grow option so that it doesn’t
run out of space if something prevents the log from being truncated By doing so, you
help avoid the need for the log file to be constantly expanded during normal processing
and also avoid excessive fragmentation of the log file If something causes the log file
to auto-grow and exceed the normal log file size, you can always manually shrink the
file back to its normal size
Long-Running Transactions
As you have already seen, transaction information is recorded in each database’s
transac-tion log However, long-running transactransac-tions can be a cause of consternatransac-tion to a system
administrator who is attempting to back up and prune the transaction log Only the
inac-tive portion of the log can be truncated during this operation The inacinac-tive portion of the
log is the pages that contain log records for all completed transactions prior to the first log
record of the oldest still-active transaction (see Figure 31.8) Even if completed
transac-tions follow the first record of the oldest active transaction, they cannot be removed from
the log until the oldest active transaction completes The reason is that the log is pruned
by clearing out entire pages of information prior to the oldest active transaction Pages
after that point cannot be cleared because they might contain records for the active
trans-action that would be needed in the event of a rollback or database recovery
In addition to preventing the log from being pruned, long-running transactions can
degrade concurrency by holding locks for an extended period of time, preventing other
Check
point
Begin
(T1)
Update
(T1)
Delete
(T1)
Begin (T2) Commit (T1)
Commit (T3) Insert
(T2) Begin (T3) Update (T3) Delete (T2) Check point Begin (T4) Update (T4) Begin (T5) Commit (T4) Insert (T2)
Inactive Portion of the
Log
Active Portion of the Log
Oldest Active Transaction (MinLSN)
FIGURE 31.8 The inactive portion of the log is the pages in the log prior to the oldest active
transaction
Trang 5CHAPTER 31 Transaction Management and the Transaction Log
OPENTRAN command, whose syntax is as follows:
DBCC OPENTRAN [(‘DatabaseName’ | DatabaseId)]
[WITH TABLERESULTS [, NO_INFOMSGS]]
The following example displays a sample of the oldest active transaction for the
bigpubs2008 database:
DBCC OPENTRAN (bigpubs2008)
go
Transaction information for database ‘bigpubs2008’
Oldest active transaction:
SPID (server process ID): 56
UID (user ID) : -1
Name : add_titles
LSN : (1926:170:6)
Start time : May 26 2009 12:17:09:220AM
SID : 0xe6810e075514c744bc8d03b34c27b004
DBCC execution completed If DBCC printed error messages, contact your system
administrator
DBCC OPENTRAN returns the server process ID (SPID) of the process that initiated the
trans-action, user ID, name of the transaction (naming transactions are helpful here because the
names might help you identify the SQL code that initiated the transaction), LSN of the
transaction was started
CREATE TABLE #opentran_results
( result_label VARCHAR(30), result_value VARCHAR(46))
insert #opentran_results
exec (‘dbcc opentran (bigpubs2008) WITH TABLERESULTS, no_infomsgs’)
select * from #opentran_results
go
Trang 6result_label result_value
——————————————— ———————————————————————
OLDACT_SPID 57
OLDACT_UID -1
OLDACT_NAME add_titles
OLDACT_LSN (1926:203:1)
OLDACT_STARTTIME May 26 2009 12:20:10:407AM
OLDACT_SID 0xe6810e075514c744bc8d03b34c27b004
If no open transactions exist for the database, you receive the following message from
DBCC OPENTRAN:
No active open transactions
DBCC execution completed If DBCC printed error messages, contact your
system administrator
DBCC OPENTRAN provides a means for you to identify which transactions are potential
prob-lems, based on their longevity If you capture the process information at the same time,
transaction(s) Using this information, you can terminate the process, if necessary, or you
can just have a quiet word with the user if the query is ad hoc or with the application
developers if it is SQL code generated by a custom application
Bound Connections
During the course of a transaction, the process that initiated the transaction acquires
exclusive locks on the data that is modified These locks prevent other user processes or
connections from seeing any of these changes until they are committed However, it is
common for some SQL Server applications to have multiple connections to SQL Server
Even though each connection might be for the same user, SQL Server treats each
connec-tion as an entirely separate SQL Server process, and by default, one connecconnec-tion cannot see
the uncommitted changes of another nor modify records locked by the other connection
Bound connections provide a means of linking multiple connections together to share the
same lock space and participate in the same transaction This capability can be useful,
especially if an application makes use of extended stored procedures Extended stored
procedures, although invoked from within a user session, run externally in a separate
session An extended stored procedure might need to call back into the database to access
data Without bound connections between the original process and extended stored
proce-dure, the extended stored procedure would be blocked by the locks held on the data by
the originating process
Trang 7CHAPTER 31 Transaction Management and the Transaction Log
NOTE
In earlier versions of SQL Server, bound sessions were primarily used in developing
extended stored procedures that needed to execute T-SQL statements on behalf of the
process calling them In SQL Server 2008, it is recommended that extended stored
procedures be replaced with stored procedures written using the common language
runtime (CLR) CLR-stored procedures are more secure, scalable, and stable than
object to join the context of the calling session rather than bound connections
Bound connections are of two types: local and distributed Local bound connections are
two or more connections within a single server that are bound into a single transaction
space Distributed bound connections make use of the Microsoft Distributed Transaction
Coordinator (MS DTC; described in more detail in the following section, “Distributed
Transactions”) to share a transaction space across connections from more than one server
Distributed Transactions
Typically, transaction management controls only the data modifications made within a
single SQL Server instance However, the increasing interest and implementation of
distributed systems brings up the need to access and modify data distributed across
multi-ple SQL Server instances within a single unit of work
What if in the banking example, the checking accounts reside on one SQL Server instance
and the savings accounts on another? Moving money from one account to another would
require updates to two separate SQL Server instances How do you modify data on two
different instances and still treat it as a single unit of work? You need some way to ensure
that the distributed transaction retains the same ACID properties as a local transaction To
provide this capability, SQL Server ships with the MS DTC service, which provides the
capability to control and manage the integrity of multiserver transactions MS DTC uses
the industry-standard two-phase commit protocol to ensure the consistency of all parts of
any distributed transaction passing through SQL Server and any referenced linked servers
Chapter 54, “Managing Linked and Remote Servers” (on the CD), covers the process of
configuring servers and writing SQL code to support distributed transactions
Trang 8Summary
A transaction is a logical unit of work as well as a unit of recovery The successful control
of transactions is of the utmost importance to the correct modification of related
informa-tion In this chapter, you learned how to define and control transactions, examined
differ-ent transaction-managemdiffer-ent schemes, learned how the recovery process works, and
discovered how to correctly code transactions within triggers and stored procedures You
also learned methods for optimizing transactions to improve application performance,
and you got an overview of locking and distributed transactions Locking is covered in
more detail in Chapter 37, and distributed transactions are covered in more detail in
Chapter 54 In addition, this chapter discussed the snapshot isolation options available in
SQL Server 2008 Snapshot isolation provides the capability to keep versions of row data
that existed prior to the start of a transaction
Chapter 32 discusses the concept of database snapshots, which provide a way to keep a
read-only, static view of a database
Trang 9This page intentionally left blank
Trang 10Database Snapshots . What’s New with Database Snapshots
Snapshots?
Database Snapshots
Snapshots
Database Snapshot
Snapshot for Recovery
a Database Mirror
Maintenance and Security Considerations
database products (Oracle and DB2) for years Database
snapshots are great for fulfilling point-in-time reporting
requirements, reverting a database back to a point in time
(recoverability and availability), and for potentially
reduc-ing the processreduc-ing impact of queryreduc-ing against your primary
transactional databases (via database mirroring and
data-base snapshots)
Keep in mind that database snapshots are point in time and
read-only Database snapshots are not materialized views
Materialized views become part of the data object (table)
that they are touching (that is, that are bound to them);
when data changes in the base tables, materialized views
change (that is, are updated) Database snapshots are
point-in-time reflections of an entire database and are not bound
to the underlying database objects from which they pull
their data They provide a full, read-only copy of the
data-base at a specific point in time Because of this
point-in-time aspect, data latency must be well understood for all
users of this feature: snapshot data is only as current as at
the time the snapshot was made
Database snapshots make huge use of Microsoft’s
copy-on-write technology In fact, the copy-on-copy-on-write technology is
the primary enabling mechanism for snapshots If you
recall from Chapter 20, “Database Mirroring,” the
copy-on-write technology is what enables database mirroring
Database snapshots can also be used in conjunction with
database mirroring to provide a highly available
transac-tional system and a reporting platform that is created from
the database mirror and offloads the reporting away from