1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft SQL Server 2008 R2 Unleashed- P141 doc

10 110 0

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

THÔNG TIN TÀI LIỆU

Cấu trúc

  • Table of Contents

  • Introduction

  • 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

      • Summary

    • 2 What’s New in SQL Server 2008

      • New SQL Server 2008 Features

      • SQL Server 2008 Enhancements

      • Summary

    • 3 Examples of SQL Server Implementations

      • Application Terms

      • OLTP Application Examples

      • DSS Application Examples

      • Summary

  • Part II: SQL Server Tools and Utilities

    • 4 SQL Server Management Studio

      • What’s New in SSMS

      • The Integrated Environment

      • Administration Tools

      • Development Tools

      • Summary

    • 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

      • Summary

    • 6 SQL Server Profiler

      • What’s New with SQL Server Profiler

      • SQL Server Profiler Architecture

      • Creating Traces

      • Executing Traces and Working with Trace Output

      • Saving and Exporting Traces

      • Replaying Trace Data

      • Defining Server-Side Traces

      • Profiler Usage Scenarios

      • Summary

  • Part III: SQL Server Administration

    • 7 SQL Server System and Database Administration

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

      • System Administrator Responsibilities

      • System Databases

      • System Tables

      • System Views

      • System Stored Procedures

      • Summary

    • 8 Installing SQL Server 2008

      • What’s New in Installing SQL Server 2008

      • Installation Requirements

      • Installation Walkthrough

      • Installing SQL Server Using a Configuration File

      • Installing Service Packs and Cumulative Updates

      • Slipstream Installations

      • Summary

    • 9 Upgrading to SQL Server 2008

      • What’s New in Upgrading SQL Server

      • Using the SQL Server Upgrade Advisor (UA)

      • Destination: SQL Server 2008 or SQL Server 2008 R2

      • Upgrading Using a Configuration File

      • Slipstreaming Upgrades

      • Upgrading Other SQL Server Components

      • Summary

    • 10 Client Installation and Configuration

      • What’s New in Client Installation and Configuration

      • Client/Server Networking Considerations

      • Client Installation

      • Client Configuration

      • Client Data Access Technologies

      • Summary

    • 11 Security and User Administration

      • What’s New in Security and User Administration

      • An Overview of SQL Server Security

      • Authentication Methods

      • Managing Principals

      • Managing Securables

      • Managing Permissions

      • Managing SQL Server Logins

      • Managing SQL Server Users

      • Managing Database Roles

      • Managing SQL Server Permissions

      • The Execution Context

      • Summary

    • 12 Data Encryption

      • What’s New in Data Encryption

      • An Overview of Data Security

      • An Overview of Data Encryption

      • SQL Server Key Management

      • Column-Level Encryption

      • Transparent Data Encryption

      • Column-Level Encryption Versus Transparent Data Encryption

      • Summary

    • 13 Security and Compliance

      • Exposure and Risk

      • Across the Life Cycle

      • The Security Big Picture

      • Identity Access Management Components

      • Compliance and SQL Server

      • SQL Server Auditing

      • Setting Up Auditing via T-SQL

      • SQL Injection Is Easy to Do

      • Summary

    • 14 Database Backup and Restore

      • What’s New in Database Backup and Restore

      • Developing a Backup and Restore Plan

      • Types of Backups

      • Recovery Models

      • Backup Devices

      • Backing Up a Database

      • Backing Up the Transaction Log

      • Backup Scenarios

      • Restoring Databases and Transaction Logs

      • Restore Scenarios

      • Additional Backup Considerations

      • Summary

    • 15 Database Mail

      • What’s New in Database Mail

      • Setting Up Database Mail

      • Sending and Receiving with Database Mail

      • Using SQL Server Agent Mail

      • Related Views and Procedures

      • Summary

    • 16 SQL Server Scheduling and Notification

      • What’s New in Scheduling and Notification

      • Configuring the SQL Server Agent

      • Viewing the SQL Server Agent Error Log

      • SQL Server Agent Security

      • Managing Operators

      • Managing Jobs

      • Managing Alerts

      • Scripting Jobs and Alerts

      • Multiserver Job Management

      • Event Forwarding

      • Summary

    • 17 Administering SQL Server 2008 with PowerShell

      • What’s New with PowerShell

      • Overview of PowerShell

      • PowerShell Scripting Basics

      • PowerShell in SQL Server 2008

      • Step-By-Step Examples

      • Summary

    • 18 SQL Server High Availability

      • What’s New in High Availability

      • What Is High Availability?

      • The Fundamentals of HA

      • Building Solutions with One or More HA Options

      • Other HA Techniques That Yield Great Results

      • High Availability from the Windows Server Family Side

      • Summary

    • 19 Replication

      • What’s New in Data Replication

      • What Is Replication?

      • The Publisher, Distributor, and Subscriber Magazine Metaphor

      • Replication Scenarios

      • Subscriptions

      • Replication Agents

      • Planning for SQL Server Data Replication

      • SQL Server Replication Types

      • Basing the Replication Design on User Requirements

      • Setting Up Replication

      • Scripting Replication

      • Monitoring Replication

      • Summary

    • 20 Database Mirroring

      • What’s New in Database Mirroring

      • What Is Database Mirroring?

      • Roles of the Database Mirroring Configuration

      • Setting Up and Configuring Database Mirroring

      • Testing Failover from the Principal to the Mirror

      • Client Setup and Configuration for Database Mirroring

      • Migrate to Database Mirroring 2008 as Fast as You Can

      • Using Replication and Database Mirroring Together

      • Using Database Snapshots from a Mirror for Reporting

      • Summary

    • 21 SQL Server Clustering

      • What’s New in SQL Server Clustering

      • How Microsoft SQL Server Clustering Works

      • Installing SQL Server Clustering

      • Summary

    • 22 Administering Policy-Based Management

      • Introduction to Policy-Based Management

      • Policy-Based Management Concepts

      • Implementing Policy-Based Management

      • Sample Templates and Real-World Examples

      • Policy-Based Management Best Practices

      • Summary

  • Part IV: Database Administration

    • 23 Creating and Managing Databases

      • What’s New in Creating and Managing Databases

      • Data Storage in SQL Server

      • Database Files

      • Creating Databases

      • Setting Database Options

      • Managing Databases

      • Summary

    • 24 Creating and Managing Tables

      • What’s New in SQL Server 2008

      • Creating Tables

      • Defining Columns

      • Defining Table Location

      • Defining Table Constraints

      • Modifying Tables

      • Dropping Tables

      • Using Partitioned Tables

      • Creating Temporary Tables

      • Summary

    • 25 Creating and Managing Indexes

      • What’s New in Creating and Managing Indexes

      • Types of Indexes

      • Creating Indexes

      • Managing Indexes

      • Dropping Indexes

      • Online Indexing Operations

      • Indexes on Views

      • Summary

    • 26 Implementing Data Integrity

      • What’s New in Data Integrity

      • Types of Data Integrity

      • Enforcing Data Integrity

      • Using Constraints

      • Rules

      • Defaults

      • Summary

    • 27 Creating and Managing Views in SQL Server

      • What’s New in Creating and Managing Views

      • Definition of Views

      • Using Views

      • Creating Views

      • Managing Views

      • Data Modifications and Views

      • Partitioned Views

      • Indexed Views

      • Summary

    • 28 Creating and Managing Stored Procedures

      • What’s New in Creating and Managing Stored Procedures

      • Advantages of Stored Procedures

      • Creating Stored Procedures

      • Executing Stored Procedures

      • Deferred Name Resolution

      • Viewing Stored Procedures

      • Modifying Stored Procedures

      • Using Input Parameters

      • Using Output Parameters

      • Returning Procedure Status

      • Debugging Stored Procedures Using SQL Server Management Studio

      • Using System Stored Procedures

      • Startup Procedures

      • Summary

    • 29 Creating and Managing User-Defined Functions

      • What’s New in SQL Server 2008

      • Why Use User-Defined Functions?

      • Types of User-Defined Functions

      • Creating and Managing User-Defined Functions

      • Rewriting Stored Procedures as Functions

      • Creating and Using CLR Functions

      • Summary

    • 30 Creating and Managing Triggers

      • What’s New in Creating and Managing Triggers

      • Using DML Triggers

      • Using DDL Triggers

      • Using CLR Triggers

      • Using Nested Triggers

      • Using Recursive Triggers

      • Summary

    • 31 Transaction Management and the Transaction Log

      • What’s New in Transaction Management

      • What Is a Transaction?

      • How SQL Server Manages Transactions

      • Defining Transactions

      • Transactions and Batches

      • Transactions and Stored Procedures

      • Transactions and Triggers

      • Transactions and Locking

      • Coding Effective Transactions

      • Transaction Logging and the Recovery Process

      • Long-Running Transactions

      • Bound Connections

      • Distributed Transactions

      • Summary

    • 32 Database Snapshots

      • 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

      • Summary

    • 33 Database Maintenance

      • What’s New in Database Maintenance

      • The Maintenance Plan Wizard

      • Managing Maintenance Plans Without the Wizard

      • Executing a Maintenance Plan

      • Maintenance Without a Maintenance Plan

      • Database Maintenance Policies

      • Summary

  • Part V: SQL Server Performance and Optimization

    • 34 Data Structures, Indexes, and Performance

      • What’s New for Data Structures, Indexes, and Performance

      • Understanding Data Structures

      • Database Files and Filegroups

      • Database Pages

      • Space Allocation Structures

      • Data Compression

      • Understanding Table Structures

      • Understanding Index Structures

      • Data Modification and Performance

      • Index Utilization

      • Index Selection

      • Evaluating Index Usefulness

      • Index Statistics

      • SQL Server Index Maintenance

      • Index Design Guidelines

      • Indexed Views

      • Indexes on Computed Columns

      • Filtered Indexes and Statistics

      • Choosing Indexes: Query Versus Update Performance

      • Identifying Missing Indexes

      • Identifying Unused Indexes

      • Summary

    • 35 Understanding Query Optimization

      • What’s New in Query Optimization

      • What Is the Query Optimizer?

      • Query Compilation and Optimization

      • Query Analysis

      • Row Estimation and Index Selection

      • Join Selection

      • Execution Plan Selection

      • Query Plan Caching

      • Other Query Processing Strategies

      • Parallel Query Processing

      • Common Query Optimization Problems

      • Managing the Optimizer

      • Summary

    • 36 Query Analysis

      • What’s New in Query Analysis

      • Query Analysis in SSMS

      • SSMS Client Statistics

      • Using the SET SHOWPLAN Options

      • Using sys.dm_exec_query_plan

      • Query Statistics

      • Query Analysis with SQL Server Profiler

      • Summary

    • 37 Locking and Performance

      • What’s New in Locking and Performance

      • The Need for Locking

      • Transaction Isolation Levels in SQL Server

      • The Lock Manager

      • Monitoring Lock Activity in SQL Server

      • SQL Server Lock Types

      • SQL Server Lock Granularity

      • Lock Compatibility

      • Locking Contention and Deadlocks

      • Table Hints for Locking

      • Optimistic Locking

      • Summary

    • 38 Database Design and Performance

      • What’s New in Database Design and Performance

      • Basic Tenets of Designing for Performance

      • Logical Database Design Issues

      • Denormalizing a Database

      • Database Filegroups and Performance

      • RAID Technology

      • SQL Server and SAN Technology

      • Summary

    • 39 Monitoring SQL Server Performance

      • What’s New in Monitoring SQL Server Performance

      • Performance Monitoring Tools

      • A Performance Monitoring Approach

      • Summary

    • 40 Managing Workloads with the Resource Governor

      • Overview of Resource Governor

      • Resource Governor Components

      • Configuring Resource Governor

      • Monitoring Resource Usage

      • Modifying Your Resource Governor Configuration

      • Summary

    • 41 A Performance and Tuning Methodology

      • The Full Architectural Landscape

      • Primary Performance and Tuning Handles

      • A Performance and Tuning Methodology

      • Performance and Tuning Design Guidelines

      • Tools of the Performance and Tuning Trade

      • Summary

  • Part VI: SQL Server Application Development

    • 42 What’s New for Transact-SQL in SQL Server 2008

      • MERGE Statement

      • Insert over DML

      • GROUP BY Clause Enhancements

      • Variable Assignment in DECLARE Statement

      • Compound Assignment Operators

      • Row Constructors

      • New date and time Data Types and Functions

      • Table-Valued Parameters

      • Hierarchyid Data Type

      • Using FILESTREAM Storage

      • Sparse Columns

      • Spatial Data Types

      • Change Data Capture

      • Change Tracking

      • Summary

    • 43 Transact-SQL Programming Guidelines, Tips, and Tricks

      • General T-SQL Coding Recommendations

      • General T-SQL Performance Recommendations

      • T-SQL Tips and Tricks

      • In Case You Missed It: New Transact-SQL Features in SQL Server 2005

      • The xml Data Type

      • The max Specifier

      • TOP Enhancements

      • The OUTPUT Clause

      • Common Table Expressions

      • Ranking Functions

      • PIVOT and UNPIVOT

      • The APPLY Operator

      • TRY...CATCH Logic for Error Handling

      • The TABLESAMPLE Clause

      • Summary

    • 44 Advanced Stored Procedure Programming and Optimization

      • T-SQL Stored Procedure Coding Guidelines

      • Using Cursors in Stored Procedures

      • Nested Stored Procedures

      • Using Temporary Tables in Stored Procedures

      • Using Remote Stored Procedures

      • Stored Procedure Performance

      • Using Dynamic SQL in Stored Procedures

      • Installing and Using .NET CLR Stored Procedures

      • Using Extended Stored Procedures

      • Summary

    • 45 SQL Server and the .NET Framework

      • What’s New in SQL Server 2008 and the .NET Framework

      • Getting Comfortable with ADO.NET 3.5 and SQL Server 2008

      • Developing with LINQ to SQL

      • Using ADO.NET Data Services

      • Leveraging the Microsoft Sync Framework

      • Summary

    • 46 SQLCLR: Developing SQL Server Objects in .NET

      • What’s New for SQLCLR in SQL Server 2008

      • Developing Custom Managed Database Objects

      • Summary

    • 47 Using XML in SQL Server 2008

      • What’s New in Using XML in SQL Server 2008

      • Understanding XML

      • Relational Data As XML: The FOR XML Modes

      • XML As Relational Data: Using OPENXML

      • Using the xml Data Type

      • Indexing and Full-Text Indexing of xml Columns

      • Summary

    • 48 SQL Server Web Services

      • What’s New in SQL Server Web Services

      • Web Services Migration Path

      • Web Services History and Overview

      • Building Web Services

      • Examples: A C# Client Application

      • Using Catalog Views and System Stored Procedures

      • Controlling Access Permissions

      • Summary

    • 49 SQL Server Service Broker

      • What’s New in Service Broker

      • Understanding Distributed Messaging

      • Designing a Sample System

      • Understanding Service Broker Constructs

      • Service Broker Routing and Security

      • Troubleshooting SSB Applications with ssbdiagnose.exe

      • Related System Catalogs

      • Summary

    • 50 SQL Server Full-Text Search

      • What’s New in SQL Server 2008 Full-Text Search

      • Upgrade Options in SQL Server 2008

      • How SQL Server FTS Works

      • Implementing SQL Server 2008 Full-Text Catalogs

      • Setting Up a Full-Text Index

      • Full-Text Searches

      • Full-Text Search Maintenance

      • Full-Text Search Performance

      • Full-Text Search Troubleshooting

      • Summary

  • Part VII: SQL Server Business Intelligence Features

    • 51 SQL Server 2008 Analysis Services

      • What’s New in SSAS

      • Understanding SSAS and OLAP

      • Understanding the SSAS Environment Wizards

      • An Analytics Design Methodology

      • An OLAP Requirements Example: CompSales International

      • Summary

    • 52 SQL Server Integration Services

      • What’s New with SSIS

      • SSIS Basics

      • SSIS Architecture and Concepts

      • SSIS Tools and Utilities

      • A Data Transformation Requirement

      • Running the SSIS Wizard

      • The SSIS Designer

      • The Package Execution Utility

      • Connection Projects in Visual Studio

      • Change Data Capture Addition with R2

      • Using bcp

      • Logged and Nonlogged Operations

      • Summary

    • 53 SQL Server 2008 Reporting Services

      • What’s New in SSRS 2008

      • Reporting Services Architecture

      • Installing and Configuring SSRS

      • Developing Reports

      • Management and Security

      • Performance and Monitoring

      • Summary

  • Part VIII: Bonus Chapters

    • 54 Managing Linked and Remote Servers

      • What’s New in Managing Linked and Remote Servers

      • Managing Remote Servers

      • Linked Servers

      • Adding, Dropping, and Configuring Linked Servers

      • Mapping Local Logins to Logins on Linked Servers

      • Obtaining General Information About Linked Servers

      • Executing a Stored Procedure via a Linked Server

      • Setting Up Linked Servers Using SQL Server Management Studio

      • Summary

    • 55 Configuring, Tuning, and Optimizing SQL Server Options

      • What’s New in Configuring, Tuning, and Optimizing SQL Server Options

      • SQL Server Instance Architecture

      • Configuration Options

      • Fixing an Incorrect Option Setting

      • Setting Configuration Options with SSMS

      • Obsolete Configuration Options

      • Configuration Options and Performance

      • Database Engine Tuning Advisor

      • Data Collection Sets

      • Summary

    • 56 SQL Server Disaster Recovery Planning

      • What’s New in SQL Server Disaster Recovery Planning

      • How to Approach Disaster Recovery

      • Microsoft SQL Server Options for Disaster Recovery

      • The Overall Disaster Recovery Process

      • Have You Detached a Database Recently?

      • Third-Party Disaster Recovery Alternatives

      • Summary

  • Index

    • A

    • B

    • C

    • D

    • E

    • F

    • G

    • H

    • I

    • J

    • K

    • L

    • M

    • N

    • O

    • P

    • Q

    • R

    • S

    • T

    • U

    • V

    • W

    • X

    • Y-Z

Nội dung

ptg 1344 CHAPTER 37 Locking and Performance table-level isolation hints within the query. Using table-level hints is covered later in this chapter, in the section “Table Hints for Locking.” Read Uncommitted Isolation If you set the Read Uncommitted mode for a session, no isolation is provided to the SELECT queries in that session. A transaction that is running with this isolation level is not immune to dirty reads, nonrepeatable reads, or phantom reads. To set the Read Uncommitted mode for a session, you run the following statements from the client: . T-SQL—Use SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED. . ODBC—Use the function call SQLSetConnectAttr with Attribute set to SQL_ATTR_TXN_ISOLATION and ValuePtr set to SQL_TXN_READ_UNCOMMITTED. . OLE DB—Use the function call ITransactionLocal::StartTransaction with the isoLevel set to ISOLATIONLEVEL_READUNCOMMITTED. . ADO—Set the IsolationLevel property of the Connection object to adXactReadUncommitted. . ADO.NET—For applications using the System.Data.SqlClient managed namespace, call the SqlConnection.BeginTransaction method and set the IsolationLevel option to ReadUncommitted. You need to be careful when running queries at Read Uncommitted isolation; it is possible to read changes that have been made to data that are subsequently rolled back. In essence, the accuracy of the results cannot be guaranteed. You should use this mode only when you need to get information quickly from an online transaction processing (OLTP) data- base, without affecting or being affected by the ongoing updates and when the accuracy of the results is not critical. Read Committed Isolation The Read Committed mode is the default locking-isolation mode for SQL Server. With Read Committed as the transaction isolation level, read operations can read pages only for transactions that have already been committed. No “dirty reads” are allowed. Locks acquired by update transactions are held for the duration of the transaction. However, in this mode, read requests within the transaction release locks as soon as the query finishes reading the data. Although this improves concurrent access to the data for updates, it does not prevent nonrepeatable reads or phantom reads. For example, within a transaction, a process could read one set of rows early in the transaction and then, before reading the information again, another process could modify the result set, resulting in a different result set being read the second time. Because Read Committed is the default isolation level for SQL Server, you do not need to do anything to set this mode. If you need to set the isolation level back to Read Committed mode for a session, you run the following statements from the client: . T-SQL—Use SET TRANSACTION ISOLATION LEVEL READ COMMITTED. Download from www.wowebook.com ptg 1345 Transaction Isolation Levels in S Q L Ser ver . ODBC—Use the function call SQLSetConnectAttr with Attribute set to SQL_ATTR_TXN_ISOLATION and ValuePtr set to SQL_TXN_READ_COMMITTED. . OLE DB—Use the function call ITransactionLocal::StartTransaction with isoLevel set to ISOLATIONLEVEL_READCOMMITTED. . ADO—Set the IsolationLevel property of the Connection object to adXactReadcommitted. . ADO.NET—For applications using the System.Data.SqlClient managed namespace, call the SqlConnection.BeginTransaction method and set the IsolationLevel option to ReadCommitted. Read Committed Snapshot Isolation When the READ_COMMITTED_SNAPSHOT database option is set to ON, sessions running with the Read Committed isolation mode use row versioning to provide statement-level read consistency. When this database option is enabled and a transaction runs at the Read Committed isolation level, all statements within the transaction see a snapshot of the data as it exists at the start of the statement. When the READ_COMMITTED_SNAPSHOT option is enabled for a database, SQL Server main- tains versions of each row that is modified. Whenever a transaction modifies a row, an image of the row before modification is copied into a page in the version store, which is a collection of data pages in tempdb. If multiple transactions modify a row, multiple versions of the row are linked in a version chain. Queries running with Read Committed Snapshot isolation retrieve the last version of each row that had been committed when the state- ment started, providing a statement-level snapshot of the data. In the Read Committed Snapshot isolation mode, read operations do not acquire shared page or row locks on the data. Therefore, readers using row versioning do not block other processes modifying the same data, and, similarly, processes modifying the data do not block the readers. In addition, because the read operations do not acquire locks, locking overhead is reduced. However, processes modifying data still block other processes modify- ing data because two operations cannot modify the same data at the same time. Exclusive locks on modified data are still acquired and held until the end of the transaction. While locking overhead is reduced for read operations when using Read Committed Snapshot isolation, it does introduce overhead to maintain the row versions in tempdb. In addition, tempdb must have sufficient space to hold the row versions in addition to the space required for normal tempdb operations. You might want to consider enabling the READ_COMMITTED_SNAPSHOT database option when blocking that occurs between read and write operations affects performance to the point that the overhead of creating and managing row versions is offset by the concurrency benefits. You may also consider using Read Committed Snapshot isolation when an appli- cation requires absolute accuracy for long-running aggregations or queries where data values must be consistent to the point in time that the query starts. 37 Download from www.wowebook.com ptg 1346 CHAPTER 37 Locking and Performance NOTE You can use Read Committed Snapshot isolation mode with most existing SQL Ser ver applications without making any change to the application code itself if the applications are written to use the default Read Committed isolation level. The behavior of Read Committed, whether to use row versioning or not, is determined by the database option setting, and this can be enabled or disabled without requiring any changes to the application code. Repeatable Read Isolation In Repeatable Read mode, SQL Server provides the same level of isolation for updates as in Read Committed mode, but it also allows the data to be read many times within the same transaction and guarantees that the same values will be read each time. Repeatable Read isolation mode prevents other users from updating data that has been read within the transaction until the transaction in which it was read is committed or rolled back. This way, the reading transaction does not pick up changes to the rows it read previously within the transaction. However, this isolation mode does not prevent additional rows (that is, phantom reads) from appearing in the subsequent reads. Although preventing nonrepeatable reads is desirable for certain transactions, it requires holding locks on the data that has been read until the transaction is completed. This reduces concurrent access for multiple update operations and causes performance degrada- tion due to lock waits and locking contention between transactions. It can also potentially lead to deadlocks. (Deadlocking is discussed in more detail in the “Deadlocks” section, later in this chapter.) To set Repeatable Read mode for a session, you run the following statements from the client: . T-SQL—Use SET TRANSACTION ISOLATION LEVEL REPEATABLE READ. . ODBC—Use the function call SQLSetConnectAttr with Attribute set to SQL_ATTR_TXN_ISOLATION and ValuePtr set to SQL_TXN_REPEATABLEREAD. . OLE DB—Use the function call ITransactionLocal::StartTransaction with isoLevel set to ISOLATIONLEVEL_REPEATABLEREAD. . ADO—Set the IsolationLevel property of the Connection object to adXact REPEAT- ABLEREAD. . ADO.NET—For applications using the System.Data.SqlClient managed namespace, call the SqlConnection.BeginTransaction method and set the IsolationLevel option to RepeatableRead. Serializable Read Isolation Serializable Read mode is similar to repeatable reads but adds to it the restriction that rows cannot be added to a result set that was read previously within a transaction. This prevents phantom reads. In other words, Serializable Read locks the existing data being read as well as rows that do not yet exist. It accomplishes this by locking the data being read. In addi- Download from www.wowebook.com ptg 1347 Transaction Isolation Levels in S Q L Ser ver tion, SQL Server puts locks on the range of values being read so that additional rows cannot be added to the range. For example, say you run a query in a transaction that retrieves all records for the Sales table in the bigpubs2008 database for a store with the stor_id of 7066. To prevent addi- tional sales records from being added to the Sales table for this store, SQL Server locks the range of values with stor_id of 7066. It accomplishes this by using key-range locks, which are discussed in the “Serialization and Key-Range Locking” section, later in this chapter. Although preventing phantom reads is desirable for certain transactions, Serializable Read mode, like Repeatable Read, reduces concurrent access for multiple update operations and can cause performance degradation due to lock waits and locking contention between transactions, and it can potentially lead to deadlocks. To set Serializable Read mode for a session, you run the following statements from the client: . T-SQL—Use SET TRANSACTION ISOLATION LEVEL SERIALIZABLE. . ODBC—Use the function call SQLSetConnectAttr with Attribute set to SQL_ATTR_TXN_ISOLATION and ValuePtr set to SQL_TXN_SERIALIZABLE. . OLE DB—Use the function call ITransactionLocal::StartTransaction with isoLevel set to ISOLATIONLEVEL_SERIALIZABLE. . ADO—Set the IsolationLevel property of the Connection object to adXact SERIALIZABLE. . ADO.NET—For applications using the System.Data.SqlClient managed namespace, call the SqlConnection.BeginTransaction method and set the IsolationLevel option to Serializable. Snapshot Isolation Snapshot Isolation is an additional isolation level available in SQL Server 2008. Similar to Read Committed Snapshot, Snapshot Isolation mode uses row versioning to take a point- in-time snapshot of the data. However, unlike Read Committed Snapshot isolation, which provides a statement-level snapshot of the data, Snapshot Isolation maintains a snapshot of the data for the duration of the entire transaction. A data snapshot is taken when the transaction starts and the snapshot remains consistent for the duration of the transaction. Snapshot Isolation mode provides the benefit of repeatable reads without acquiring and holding shared locks on the data that is read. This can help minimize locking and block- ing problems between read operations and update operations. Read operations do not have to wait for write operations and writes don’t have to wait for reads. To set the Snapshot Isolation mode for a session, you run the following statement: SET TRANSACTION ISOLATION LEVEL SNAPSHOT 37 Download from www.wowebook.com ptg 1348 CHAPTER 37 Locking and Performance In addition, to be able to request the Snapshot Isolation mode in a session, you must enable the database option ALLOW_SNAPSHOT_ISOLATION with the ALTER DATABASE command: ALTER DATABASE dbname SET ALLOW_SNAPSHOT_ISOLATION ON When Snapshot Isolation mode is enabled, SQL Server assigns a transaction sequence number to each transaction that manipulates data using row versioning. When either the READ_COMMITTED_SNAPSHOT or ALLOW_SNAPSHOT_ISOLATION database option is set to ON, SQL Server stores a version of the previously committed image of the data row in tempdb whenever the row is modified by a transaction. Each of these versions is marked with the transaction sequence number of the transaction that made the change. The versions of the modified rows are linked together in a chain, with the most recent version of the row always stored in the current database and the versioned rows stored in tempdb. When a transaction requests a read of data, it searches the version chain to locate the last committed version of the data row with a lower transaction sequence number than the current transaction. Row versions are kept in tempdb only long enough to satisfy the requirements of any transactions running under row versioning–based isolation levels. SQL Server keeps track of the sequence number of the oldest outstanding transaction and period- ically deletes all row versions stamped with transaction sequence numbers lower than that. You might consider using snapshot isolation in the following instances: . When you want optimistic concurrency control . When it is unlikely that your transaction would have to be rolled back because of an update conflict . When an application generates reports based on long-running, multistatement queries that must have point-in-time consistency . With systems that are incurring a high number of deadlocks because of read/write contention There is a risk to using snapshot isolation, however. If two client applications both retrieve the same data and then both attempt to write changes to the data back to the database, the second application could potentially overwrite the first application’s changes. This is called a lost update error. Fortunately, SQL Server 2008 resolves this problem by blocking the second transaction’s writes. So, although snapshot isolation provides benefits for resolving conflicts between read and write operations, there can still be conflicts between multiple write operations. For systems with heavy read and insert activity and with little concurrent updating of the same resource, snapshot isolation can provide a solution for concurrency issues. Another cost of snapshot isolation is that it can make heavy use of tempdb. For this reason, you should locate tempdb on its own high-performance drive system. Download from www.wowebook.com ptg 1349 The Lock Manager NOTE Only one of the transaction isolation levels can be active at any given time for a user session. The isolation level you set within an application is active for the duration of the connection or until it is manually reset. To check the current transaction isolation level settings, you run the DBCC USEROPTIONS command and examine the value for isolation level, as in the following example: DBCC USEROPTIONS go Set Option Value textsize 2147483647 language us_english dateformat mdy datefirst 7 lock_timeout -1 quoted_identifier SET arithabort SET ansi_null_dflt_on SET ansi_warnings SET ansi_padding SET ansi_nulls SET concat_null_yields_null SET isolation level snapshot Be aware that DBCC USEROPTIONS reports an isolation level of Read Committed Snapshot when the database option READ_COMMITTED_SNAPSHOT is set to ON and the current transaction isolation level is set to Read Committed. The actual isolation level in effect for the user session is Read Committed. The Lock Manager The responsibility for ensuring lock conflict resolution between user processes falls on the SQL Server Lock Manager. SQL Server automatically assigns locks to processes to guarantee that the current user of a resource (for example, a data row or page, an index row or page, a table, an index, or a database) has a consistent view of that resource, from the beginning to the end of a particular operation. In other words, what you start with is what you work with throughout your transaction. Nobody can change what you are working on in midstate, thereby ensuring the consistency of your transaction. 37 Download from www.wowebook.com ptg 1350 CHAPTER 37 Locking and Performance The Lock Manager is responsible for deciding the appropriate lock type (for example, shared, exclusive, update) and the appropriate granularity of locks (for example, row, page, table), according to the type of operation being performed and the amount of data being affected. Based on the type of transaction, the SQL Server Lock Manager chooses different types of lock resources. For example, a CREATE INDEX statement might lock the entire table, whereas an UPDATE statement might lock only a specific row. The Lock Manager also manages compatibility between lock types attempting to access the same resources, resolves deadlocks, and escalates locks to a higher level, if necessary. The Lock Manager manages locks for both shared data and internal system resources. For shared data, the Lock Manager manages row locks, page locks, and table locks on tables, as well as data pages, text pages, and leaf-level index pages. Internally, the Lock Manager uses latches to manage locking on index rows and pages, controlling access to internal data structures and, in some cases, for retrieving individual rows of data. Latches provide better system performance because they are less resource intensive than locks. Latches also provide greater concurrency than locks. Latches are typically used for operations such as page splits, deletion of index rows, movement of rows in an index, and so on. The main difference between a lock and a latch is that a lock is held for the duration of the transac- tion, and a latch is held only for the duration of the operation for which it is required. Locks are used to ensure the logical consistency of data, whereas latches are used to ensure the physical consistency of the data and data structures. The remainder of this chapter examines how the Lock Manager determines the type and level of lock to assign, based on the type of command being executed, number of rows affected, and lock isolation level in effect. Monitoring Lock Activity in SQL Server To monitor the performance of a system, you need to keep track of locking activity in SQL Server. The following are the most commonly used methods to do so: . Querying the sys.dm_tran_locks dynamic management view directly . Viewing locking activity with SQL Server Profiler . Monitoring locks with Performance Monitor As you read through the rest of this chapter, you might want to examine or monitor the locking activity for the examples presented. To assist you in that effort, the following sections describe the methods of examining lock activity in SQL Server 2008. Querying the sys.dm_tran_locks View The sys.dm_tran_locks dynamic management view returns information about all the locks currently granted or waiting to be granted in SQL Server. (The information is popu- lated from the internal lock management structures in SQL Server 2008.) This view provides no historical information; rather, the data in this view corresponds to live Lock Download from www.wowebook.com ptg 1351 Monitoring Lock Activity in SQL Server Manager information. This data can change at any time for subsequent queries of the view as locks are acquired and released. The information returned by the view can be divided into two main groups: resource information and lock request information. The resource information describes the resource on which the lock request is being made, and the request information provides details on the lock request itself. Table 37.1 describes the most useful data columns returned by the sys.dm_tran_locks view. 37 TABLE 37.1 Useful Columns Returned by the sys.dm_tran_locks View Column Name Description resource_type Indicates the type of resource the lock is being held or requested on. resource_subtype Indicates a subtype of the resource_type, if any. resource_database_id Indicates the database ID of the database where the resource resides. resource_description Provides information about the resource that is not available from other resource columns. resource_associated_entity_id Indicates the ID of the entity in a database that the resource is associated with. resource_lock_partition Indicates the ID of the associated partition for a resource that is partitioned. request_mode Indicates the lock mode of the request that has been granted or is being waited on. request_type Indicates the request type. (The only current value is LOCK.) request_status Indicates the current status of this request (GRANT, CONVERT, or WAIT). request_reference_count Returns an approximate number of times the same requestor has requested this resource. request_lifetime Specifies a code indicating when the lock on the resource is released. request_session_id Indicates the ID of the session that generated the corresponding request. request_exec_context_id Indicates the ID of the execution context of the process that generated the lock request. Download from www.wowebook.com ptg 1352 CHAPTER 37 Locking and Performance Table 37.2 lists the possible lock request modes that can be displayed in the request_mode column of the sys.dm_tran_locks view. TABLE 37.1 Useful Columns Returned by the sys.dm_tran_locks View Column Name Description request_request_id Indicates the batch ID of the process that gener- ated the request. request_owner_type Indicates the type of entity that owns the request. Possible values include, but are not limited to, TRANSACTION, CURSOR, and SESSION. request_owner_id Specifies the ID of the specific owner of this request. This value is used for transactions for which this is the transaction ID. request_owner_guid Indicates the GUID of the specific owner of the lock request. This value is used only by a distrib- uted transaction where the value corresponds to the MS DTC GUID for that transaction request_owner_lockspace_id Represents the lockspace ID of the requestor. The lockspace ID determines whether two requestors are compatible with each other and can be granted locks in modes that would otherwise conflict with one another. lock_owner_address Indicates the memory address of the internal data structure used to track the request. TABLE 37.2 Lock Request Modes Value Lock Type Description Request Mode 1 N/A No access provided to the requestor NULL 2 Schema Schema stability lock Sch-S 3 Schema Schema modification lock Sch-M 4 Shared Acquisition of a shared lock on the resource S 5 Update Acquisition of an update lock on the resource U 6 Exclusive Exclusive lock granted on the resource X 7 Intent Intent for a shared lock IS 8 Intent Intent for an update lock IU 9 Intent Intent for an exclusive lock IX Download from www.wowebook.com ptg 1353 Monitoring Lock Activity in SQL Server 37 Listing 37.1 provides an example of a query against the sys.dm_tran_locks view. LISTING 37.1 An Example of a Query Against the sys.dm_tran_locks View select str(request_session_id, 4,0) as spid, convert (varchar(12), db_name(resource_database_id)) As db_name, case when resource_database_id = db_id() and resource_type = ‘OBJECT’ then convert(char(20), object_name(resource_Associated_Entity_id)) else convert(char(20), resource_Associated_Entity_id) TABLE 37.2 Lock Request Modes Value Lock Type Description Request Mode 10 Intent Shared lock with intent for an update lock on subordinate resources SIU 11 Intent Shared lock with intent for an exclusive lock on subordinate resources SIX 12 Intent Update lock with an intent for an exclusive lock on subordi- nate resources UIX 13 Bulk BULK UPDATE lock used for bulk copy operations BU 14 Key-Range Shared lock on the range between keys and shared lock on the key at the end of the range; used for serializable range scan Range_S_S 15 Key-Range Shared lock on the range between keys, with an update lock on the key at the end of the range Range_S_U 16 Key-Range Exclusive lock used to prevent inserts into a range between keys RangeIn-N 17 Key-Range Key-range conversion lock created by overlap of RangeIn-N and shared (S) locks RangeIn-S 18 Key-Range Key-range conversion lock created by overlap of RangeIn-N and update (U) locks RangeIn-U 19 Key-Range Key-range conversion lock created by overlap of RangeIn-N and exclusive (X) locks RangeIn-X 20 Key-Range Key-range conversion lock created by overlap of RangeIn-N and RangeS_S locks RangeX-S 21 Key-Range Key-Range conversion lock created by overlap of RangeIn-N and RangeS_U locks RangeX-U 22 Key-Range Exclusive lock on range between keys, with an exclusive lock on the key at the end of the range RangeX-X Download from www.wowebook.com . SQL Server 2008. Querying the sys.dm_tran_locks View The sys.dm_tran_locks dynamic management view returns information about all the locks currently granted or waiting to be granted in SQL Server. . client: . T -SQL Use SET TRANSACTION ISOLATION LEVEL REPEATABLE READ. . ODBC—Use the function call SQLSetConnectAttr with Attribute set to SQL_ ATTR_TXN_ISOLATION and ValuePtr set to SQL_ TXN_REPEATABLEREAD. client: . T -SQL Use SET TRANSACTION ISOLATION LEVEL SERIALIZABLE. . ODBC—Use the function call SQLSetConnectAttr with Attribute set to SQL_ ATTR_TXN_ISOLATION and ValuePtr set to SQL_ TXN_SERIALIZABLE. .

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

TỪ KHÓA LIÊN QUAN