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

Microsoft SQL Server 2008 R2 Unleashed- P89 doc

10 183 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 824 FIGURE 26.3 Constraints in Object Explorer. FIGURE 26.4 A new CHECK constraint in Object Explorer. CHAPTER 26 Implementing Data Integrity of the constraints (PRIMARY KEY, UNIQUE, and FOREIGN KEY) are actually contained under the Keys node. When you select the New Constraint option from the Object Explorer, the Check Constraints dialog, shown in Figure 26.4, appears. This dialog gives you the option to define a new CHECK constraint on the table selected. You simply fill in a valid expression for the constraint, give it a unique name, and select the options you want. Download from www.wowebook.com ptg 825 Using Constraints 26 FIGURE 26.5 A new FOREIGN KEY constraint in Object Explorer. Similarly, you can right-click the Keys node and select New Foreign Key to add a new FOREIGN KEY constraint. Figure 26.5 shows the Foreign Key Relationships dialog displayed after you select New Foreign Key. You click the ellipsis to the right of Tables and Columns Specification, and you can select the primary key table you want the foreign key to relate to. Finally, you select the desired options, and you are ready to add your new FOREIGN KEY constraint. TIP When you use the Object Explorer to add or modify constraints, two windows are impor- tant to this process. The first window is the Constraint window, which allows you to input the constraint information. The Table Designer window that displays the column properties for the table is the other window that is important to the change process. It is launched in the background, and you can view it on the tabbed display of SSMS. When you make changes using the Constraint window, those changes are not applied via SSMS until the Table Designer window is closed. This may cause some confusion because even though you close your Constraint window with your changes, those changes may not be reflected in the database. You must close the Table Designer win- dow to be able to actually make the changes to the table. When you close the Table Designer window, a prompt appears, asking whether you want to save the changes to the table. If you click Yes, your constraint changes are applied to the database. If you click No, none of the constraint changes you have made are applied. You can also use the Table Designer menu to script out the related changes and apply them manually via a database engine query window. The Database Diagram Editor is another great visual tool for adding constraints. This tool is particularly useful for viewing and adding foreign key relationships to tables. Consider, for example, the database diagram shown in Figure 26.6. This diagram shows the AddressType and BusinessEntityAddress tables and the relationships that exist between Download from www.wowebook.com ptg 826 CHAPTER 26 Implementing Data Integrity FIGURE 26.6 Adding constraints by using a database diagram. them. To add a new relationship, you right-click the table you want to add the foreign key to and select the Relationships option. After you fill in the appropriate information for the relationship, you can generate a change script by using the Table Designer menu, or you can simply close the database diagram window and respond to the prompt to save changes. You can also see options to add other constraints, such as CHECK constraints, by right-clicking the table in the database diagram and selecting the desired option. You can also launch windows for adding constraints from the Table Designer menu. To enable the Table Designer menu, you right-click the table in Object Explorer that you want to add constraints to and select the Design option. The table and column properties are displayed, and the Table Designer menu is enabled. The Table Designer menu includes options to manage relationships, indexes/keys, and CHECK constraints. TIP It is a good idea to generate a script to implement changes made using SSMS visual tools. You can review the script for accuracy, run it at a later time, and save it in a file to keep track of the changes. You can also apply the saved script to other environ- ments, if needed. Download from www.wowebook.com ptg 827 Using Constraints 26 FIGURE 26.7 Executing sp_helpconstraint on the Customer table. Managing Constraints Managing constraints consists of gathering information about constraints, disabling and re-enabling constraints, and dropping constraints. These actions are discussed in the following sections. Gathering Constraint Information You can obtain information about constraints by using the visual tools, system stored procedures, and information_schema views. The visual tools (including the Object Explorer, Table Designer, and database diagrams) were introduced in the previous section. These tools offer a simple, user-friendly means for obtaining information related to constraints. These tools allow you to view a table’s constraints and display the relative information. The sp_help and sp_helpconstraint system stored procedures are another good source of information about constraints. Like the visual tools, these procedures allow you to gather constraint information about a specific table. The sp_helpconstraint procedure provides the most concise information related to constraints. Figure 26.7 shows the sp_helpconstraint output for the Sales.Customer table. You need to make sure to enclose the table name in brackets, as shown here, when the schema name is included. The output from sp_helpconstraint includes all the constraints for the table, and it supplies a list of tables that have foreign key references to the table. Download from www.wowebook.com ptg 828 CHAPTER 26 Implementing Data Integrity Catalog views offer a flexible alternative for returning information about constraints. SQL Server Books Online recommends using the sys.key_constraints, sys.check_constraints, and sys.default_constraints catalog views. These catalog views allow you to obtain constraint information for more than one table at a time. They are very flexible and allow you to customize the type of data you want to return simply by adjusting the selection criterion. Listing 26.4 shows a sample SELECT statement for each of the catalog views related to constraints and the resulting output. The SELECT statements in this example have a WHERE clause in them that limits the results to the SalesTax table, but you can remove this clause to retrieve constraints for all the tables. LISTING 26.4 Using Catalog Views to Display Constraint Information select LEFT(name,30) NAME, type from sys.key_constraints where object_name(parent_object_id) = 'SalesTaxRate' order by 1 select LEFT(name,30) NAME, type from sys.check_constraints where object_name(parent_object_id) = 'SalesTaxRate' order by 1 select LEFT(name,30) NAME, type from sys.default_constraints where object_name(parent_object_id) = 'SalesTaxRate' order by 1 /* Results of the previous SELECT statements NAME type PK_SalesTaxRate_SalesTaxRateID PK (1 row(s) affected) NAME type CK_SalesTaxRate_TaxType C (1 row(s) affected) NAME type DF_SalesTaxRate_ModifiedDate D DF_SalesTaxRate_rowguid D DF_SalesTaxRate_TaxRate D Download from www.wowebook.com ptg 829 Using Constraints 26 (3 row(s) affected) */ Dropping Constraints You can drop constraints by using the visual tools or by using T-SQL. You can right-click a constraint in the Object Explorer and select the Delete option to drop that constraint. The Object Explorer also offers a script option that generates the T-SQL statements used to drop the constraint. The ALTER TABLE command is the T-SQL command you use to make the change. For example, to drop the CK_Employee_Gender constraint on the Employee table, you can use the following command: ALTER TABLE [HumanResources].[Employee] DROP CONSTRAINT [CK_Employee_Gender] You should use caution when dropping constraints because some constraints affect other tables. For example, if you drop the PRIMARY KEY constraint on a table and that table is referenced by foreign keys, the drop statement fails. Disabling Constraints You can disable CHECK and FOREIGN KEY constraints by using the NOCHECK clause. This capability allows you to stop the constraints from being checked without removing the constraints from your database. The following ALTER TABLE command allows you to disable the FK_Customer_SalesTerritory_TerritoryID foreign key constraint on the Customer table: ALTER TABLE Sales.Customer NOCHECK CONSTRAINT FK_Customer_SalesTerritory_TerritoryID When the constraint is disabled, it no longer performs validation. You should disable constraints with caution because the integrity of your data can be compromised. In the previous example, disabling the FOREIGN KEY constraint would allow an invalid TerritoryID to be inserted in the Customer table. Why would you disable constraints? One possible reason would be to disable the constraints during large data loads. The execution of constraints can slow the load process. To facilitate the fastest load speed, you can disable constraints and then re-enable them when the data load is complete. To re-enable a constraint, you use the CHECK keyword in the ALTER TABLE statement. The following example re-enables the FOREIGN KEY constraint for the Customer table: ALTER TABLE Sales.Customer CHECK CONSTRAINT FK_Customer_SalesTerritory_TerritoryID Download from www.wowebook.com ptg 830 CHAPTER 26 Implementing Data Integrity Keep in mind that enabling a constraint does not necessarily mean the underlying data is being validated against the constraint. In fact, the default behavior when enabling a constraint in SQL Server 2008 is not to check the data against the constraint when a constraint in enabled. The default behavior when a constraint is added is to validate the data. You can force the data in the table to be validated using the WITH CHECK option. The following WITH CHECK option could be used to force the validation of the underlying data when a constraint is enabled: ALTER TABLE Sales.Customer WITH CHECK CHECK CONSTRAINT FK_Customer_SalesTerritory_TerritoryID Rules You can use rules as another method to enforce domain integrity. Rules are similar to CHECK constraints but have some limitations. The biggest advantage when using a rule is that one rule can be bound to multiple columns or user-defined data types. This capability can be useful for columns that contain the same type of data and are found in multiple tables in a database. The syntax for creating a rule is as follows: CREATE RULE [ schema_name . ] rule_name AS condition_expression [ ; ] condition_expression can include any statement that can be placed in a WHERE clause. It includes one variable that is preceded with the @ symbol. This variable contains the value of the bound column that is supplied with the INSERT or UPDATE statement. The name of the variable is not important, but the conditions and formatting within the expression are. Only one variable can be referenced per rule. The following example illustrates the creation of a rule that could be used to enforce the format of data inserted in phone number columns: CREATE RULE phone_rule AS @phone LIKE ‘([0-9][0-9][0-9]) [0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]’ The variable in the condition expression is @phone, and it contains the inserted or updated value for any column that the rule is bound to. The following example binds the phone_rule rule to the PhoneNumber column in the person.PersonPhone table: sp_bindrule phone_rule, 'Person.PersonPhone.PhoneNumber’ When a rule is bound to a column, any future insertions or updates to data in the bound column are constrained by the rule. Existing data is not affected at the time the rule is bound to the column. For example, many different phone number formats in the person.PersonPhone table do not conform to phone_rule, but phone_rule can be bound to this table successfully. To illustrate this point, the following UPDATE statement can be Download from www.wowebook.com ptg 831 Defaults 26 run against the person.PersonPhone table after the phone_rule rule is bound to the PhoneNumber column: update person.contact set phone = phone The preceding update sets the PhoneNumber value to itself, but this causes phone_rule to execute. The following error message is displayed after the update is run because the exist- ing data in the person.contact table violates the phone_rule rule: Msg 513, Level 16, State 0, Line 2 A column insert or update conflicts with a rule imposed by a previous CREATE RULE statement. The statement was terminated. The conflict occurred in database ‘Adventureworks2008’, table ‘PersonPhone’, column ‘PhoneNumber’. The statement has been terminated. Although rules are powerful objects, Microsoft has slated them for removal in a future version of SQL Server. Microsoft recommends using CHECK constraints on each column instead of rules. CHECK constraints provide more flexibility and a consistent approach, and multiple CHECK constraints can be applied to a single column. Defaults A default provides a value for a column when a value is not supplied. Defaults can be anything that evaluates to a constant, such as a constant, built-in function, or mathemati- cal expression. Defaults are of two types: declarative and bound. The two types are func- tionally the same; the difference is in how they are implemented. Declarative Defaults A declarative default is a constraint defined as part of the table definition. Using declara- tive defaults is the preferred method for assigning default values to columns. You can use the CREATE TABLE or ALTER TABLE statement to create a default and assign it to a column. Declarative defaults are assigned to a single column and cannot be reused for other columns in the database. The following example shows the creation of a new column namedCustomerType in the SalesCustomer table followed by the creation of a new default on that column: ALTER TABLE Sales.Customer ADD CustomerType CHAR(1) ALTER TABLE Sales.Customer ADD CONSTRAINT Download from www.wowebook.com ptg 832 CHAPTER 26 Implementing Data Integrity DF_Customer_CustomerType DEFAULT ‘I’ FOR CustomerType It is important to remember that a default constraint stores the default value only when a value is not provided during the insertion of a row into the table. The creation of a default constraint does not affect the existing data in the table. UPDATE statements do not utilize the values specified in the default constraint, either, unless the DEFAULT keyword is explic- itly referenced; this issue is discussed later in this chapter, in the section “When a Default Is Applied.” Generally, the only time a default comes into play is when the row is initially inserted. The following example shows an INSERT statement that causes the default value defined in the DF_Customer_CustomerType constraint to be used: INSERT Sales.Customer (TerritoryID) SELECT TOP 1 TerritoryID from Sales.SalesTerritory select CustomerID, CustomerType from Sales.Customer where CustomerID = @@identity /*Results from previous select statement CustomerID CustomerType —————- —————— 30119 I */ The Sales.Customer table in the Adventureworks2008 database is an interesting table because most of the columns have defaults defined, are identity columns, or are nullable. This table has eight columns, but only one value is supplied in the previous example. The rest of the columns, including the CustomerType column, have default definitions that automatically populate the values upon insertion or default to null. One common misconception with defaults is that a default value is stored when a NULL value is supplied for a column on insertion. However, NULL is considered a value, so the default value is not used in this situation. This is demonstrated in the following example, where the CustomerType column is altered to accept NULL values and then a NULL value is specified for the CustomerType column in the INSERT statement: ALTER TABLE Sales.Customer ALTER COLUMN CustomerType nchar(1) null INSERT Sales.Customer (TerritoryID, CustomerType) SELECT TOP 1 TerritoryID, null from Sales.SalesTerritory The insertion in this example succeeds, and the Null value is stored in the CustomerType column that has a default defined on it. Download from www.wowebook.com ptg 833 Defaults 26 To remove a declarative default constraint, you use ALTER TABLE with the DROP CONSTRAINT clause. The following example removes the DF_Customer_CustomerType constraint from the Sales.Customer table: ALTER TABLE Sales.Customer DROP CONSTRAINT DF_Customer_CustomerType Bound Defaults Bound defaults are similar to rules in that you first create a bound default and then bind it to a column or set of columns. Bound defaults are also similar to rules in that they are slated for removal in a future version of SQL Server. This section covers the basics of bound defaults, but you should keep in mind that Microsoft recommends you avoid using them for new development work. You use the CREATE DEFAULT command to establish a default that can be bound to a column at a later time. The CREATE DEFAULT syntax is as follows: CREATE DEFAULT [ schema_name . ] default_name AS constant_expression [ ; ] constant_expression can include any constant, built-in function, or mathematical expression. It cannot include user-defined functions. Character and data values that are part of the expression should be enclosed in single quotation marks. Monetary, integer, and floating-point constants do not require the single quotation marks. The following example creates a default named password_df that can be used to supply a default password for any password-oriented columns: CREATE DEFAULT password_df AS ‘defaultpw’ After you create a default, you can bind it to a column. The following example binds the password_df default to the passwordSalt column on the person.password table: sp_bindefault password_df, ‘person.password.PasswordSalt’ As you can see, a bound default appears to require an extra step, but after it is created, it offers an advantage: you can bind it to other columns. This capability provides some consistency across all the columns that the default is bound to and reduces the overall number of database objects. When a Default Is Applied Defaults are applied only when no value is specified for a column during an insertion. They can also be applied during insertions and updates when the DEFAULT keyword is used. To demonstrate the application of defaults, consider the following examples: CREATE TABLE test_default (id int IDENTITY NOT NULL, Download from www.wowebook.com . ‘Adventureworks2008’, table ‘PersonPhone’, column ‘PhoneNumber’. The statement has been terminated. Although rules are powerful objects, Microsoft has slated them for removal in a future version of SQL Server. . validated against the constraint. In fact, the default behavior when enabling a constraint in SQL Server 2008 is not to check the data against the constraint when a constraint in enabled. The default. are slated for removal in a future version of SQL Server. This section covers the basics of bound defaults, but you should keep in mind that Microsoft recommends you avoid using them for new

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