Microsoft SQL Server 2008 R2 Unleashed- P110 pptx

10 520 0
Microsoft SQL Server 2008 R2 Unleashed- P110 pptx

Đang tải... (xem toàn văn)

Thông tin tài liệu

ptg 1034 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. 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: . No checkpoint has taken place yet since the log was last truncated, and the log records are needed for database recovery. . A database or log backup is in progress. . A long-running transaction is still active. . Database mirroring is paused. (For more information, see Chapter 20, “Database Mirroring.”) . The database is the primary database for transactional replication, and transactions relevant to the publications have not yet been delivered to the distribution database. (For more information on replication, see Chapter 19, “Replication.”) . A database snapshot is being created (for more information, see Chapter 32, “Database Snapshots”). If something is preventing the log from being truncated, SQL Server 2008 provides infor- mation in the system catalogs to determine what is preventing log truncation. This infor- mation is available in the log_reuse_wait_desc column of the sys.databases catalog 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 Download from www.wowebook.com ptg 1035 Transaction Logging and the Recover y Process 31 file. 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. SQL Server 2008 provides the DBCC SHRINKFILE command for shrinking the transaction log file. Its syntax is as follows: DBCC SHRINKFILE ( { ’file_name’ } { [,EMPTYFILE] | [,target_size ] } ) [ WITH NO_INFOMSGS ] If no target size is specified for the DBCC SHRINKFILE command, SQL Server removes as 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 is the size specified when the log file was created or the last size set by using the ALTER DATABASE command. If a target size is specified for DBCC SHRINKFILE, SQL Server attempts to remove as many 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. If no VLFs beyond the target_size mark contain an active portion of the log, all the VLFs that come after the target_size mark are freed, and the DBCC SHRINKFILE statement completes successfully, with no messages. However, if any VLF beyond the target_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. When this occurs, the DBCC SHRINKFILE command returns an informational message indi- cating that not all the requested space was freed. When the active portion of the log moves off the VLF(s) at the end of the physical log file, you can reissue the DBCC SHRINK- FILE statement again to free the remaining space. You can also use SQL Server Management Studio (SSMS) to shrink the transaction log file. In the Object Browser, expand the Databases folder and right-click the target database. Then select Tasks, Shrink, and Files. The Shrink File dialog appears, as shown in Figure 31.7. Download from www.wowebook.com ptg 1036 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 option, AUTO_SHRINK, that can be enabled to shrink the log and database files automati- cally when space is available at the end of the file. If you are regularly backing up or trun- cating the log, the AUTO_SHRINK option keeps the size of the log file in check. The 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. FIGURE 31.7 The SSMS Shrink File dialog. Download from www.wowebook.com ptg 1037 Long-Running Transactions 31 TIP 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 instead of using AUTO_SHRINK, you set the transaction log to the size it is expected to 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 transactions can be a cause of consternation 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 inactive 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 users from accessing the locked data. 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. Download from www.wowebook.com ptg 1038 CHAPTER 31 Transaction Management and the Transaction Log To get information about the oldest active transaction in a database, you can use the DBCC 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 page containing the initial BEGIN TRAN statement for the transaction, and, finally, time the transaction was started. If you specify the TABLERESULTS option, this information is returned in two columns that you can load into a table for logging or comparison purposes. The NO_INFOMSGS option suppresses the display of the ’DBCC execution completed ’ message. The following example runs DBCC OPENTRAN and inserts the results into a temp table: 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 Download from www.wowebook.com ptg 1039 Bound Connections 31 result_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, using sp_who, you can identify who or what application is causing the longest-running 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 connection 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. Download from www.wowebook.com ptg 1040 CHAPTER 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 extended stored procedures. In addition, CLR-stored procedures use the SqlContext 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. Download from www.wowebook.com ptg 1041 Summary 31 Summary 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-management 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. Download from www.wowebook.com ptg This page intentionally left blank Download from www.wowebook.com ptg CHAPTER 32 Database Snapshots IN THIS CHAPTER . What’s New with Database Snapshots . What Are Database Snapshots? . Limitations and Restrictions of Database Snapshots . Copy-on-Write Technology . When to Use Database Snapshots . Setup and Breakdown of a Database Snapshot . Reverting to a Database Snapshot for Recovery . Setting Up Snapshots Against a Database Mirror . Database Snapshots Maintenance and Security Considerations Database snapshots have been a feature of competing 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 processing impact of querying 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-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 Download from www.wowebook.com . 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. 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, . 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

Ngày đăng: 05/07/2014, 02:20

Mục lục

  • Part I: Welcome to Microsoft SQL Server

    • 1 SQL Server 2008 Overview

      • SQL Server Components and Features

      • SQL Server 2008 R2 Editions

      • SQL Server Licensing Models

      • 2 What’s New in SQL Server 2008

        • New SQL Server 2008 Features

        • 3 Examples of SQL Server Implementations

          • Application Terms

          • Part II: SQL Server Tools and Utilities

            • 4 SQL Server Management Studio

              • What’s New in SSMS

              • 5 SQL Server Command-Line Utilities

                • What’s New in SQL Server Command-Line Utilities

                • The sqlcmd Command-Line Utility

                • The dta Command-Line Utility

                • The tablediff Command-Line Utility

                • The bcp Command-Line Utility

                • The sqldiag Command-Line Utility

                • The sqlservr Command-Line Utility

                • 6 SQL Server Profiler

                  • What’s New with SQL Server Profiler

                  • SQL Server Profiler Architecture

                  • Executing Traces and Working with Trace Output

                  • Saving and Exporting Traces

                  • Part III: SQL Server Administration

                    • 7 SQL Server System and Database Administration

                      • What’s New in SQL Server System and Database Administration

                      • 8 Installing SQL Server 2008

                        • What’s New in Installing SQL Server 2008

                        • Installing SQL Server Using a Configuration File

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan