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

Microsoft SQL Server 2008 R2 Unleashed- P81 pptx

10 319 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 744 FIGURE 24.2 Using database diagrams to create a table. the AdventureWorks2008 database was added to the diagram, and a new Printer table was added as well. The printer table was added by right-clicking in the diagram design window and selecting the New Table option. CHAPTER 24 Creating and Managing Tables The column names and related attributes for the new Printer table in Figure 24.2 were added using the table entry fields. The data entry screen for the table is similar to the one provided with the Object Explorer. You enter column names, along with their associated data types and nullability option. The advantage of database diagrams is that you can define relationships and show them with a visual representation. This visual view provides a much easier way to view the table structures in a database. In the example shown in Figure 24.2, the line drawn between the Department and Printer tables represents a relationship between these two tables. You define such a foreign key relationship in the database diagram by dragging the related column from one table to the other related table. Table relationships and constraints are discussed later in this chapter, in the section “Defining Table Constraints.” Using T-SQL to Create Tables Ultimately, all the tables created with the visual tools can also be created by using T-SQL. As with many of the SSMS tools, database objects can be resolved or scripted into T-SQL statements. Let’s examine the T-SQL syntax to better understand some of the table creation options; then we can discuss the definition of the columns in each table. Download from www.wowebook.com ptg 745 Creating Tables 24 The full T-SQL CREATE TABLE syntax is extensive. It includes options to define table constraints, indexes, and index options. SQL Server Books Online shows the full syntax and describes each of these options in detail. Listing 24.1 shows the basic T-SQL syntax; the first part of the syntax is listed in Books Online. This syntax is enough to enable you to create a table with its associated column definitions. LISTING 24.1 Basic T-SQL CREATE TABLE Syntax CREATE TABLE [ database_name . [ schema_name ] . | schema_name . ] table_name ( { <column_definition> | <computed_column_definition> } [ <table_constraint> ] [ , n ] ) [ ON { partition_scheme_name ( partition_column_name ) | filegroup | “default” } ] [ { TEXTIMAGE_ON { filegroup | “default” } ] [ ; ] <column_definition> ::= column_name <data_type> [ COLLATE collation_name ] [ NULL | NOT NULL ] [ [ CONSTRAINT constraint_name ] DEFAULT constant_expression ] | [ IDENTITY [ ( seed ,increment ) ] [ NOT FOR REPLICATION ] ] [ ROWGUIDCOL ] [ <column_constraint> [ n ] ] <data type> ::= [ type_schema_name . ] type_name [ ( precision [ , scale ] | max | [ { CONTENT | DOCUMENT } ] xml_schema_collection ) ] The number of options in this basic syntax can be daunting, but the reality is that you can exclude many of the options and execute a relatively simple statement. Listing 24.2 is an example of a simple statement you can use to create a table. This listing shows a CREATE TABLE statement that you can use to create the Printers table that was shown in Figure 24.2. LISTING 24.2 A Basic T-SQL CREATE TABLE Example CREATE TABLE Printer ( PrinterID int NOT NULL, DepartmentID smallint NOT NULL, PrinterName varchar(50) NOT NULL, Download from www.wowebook.com ptg 746 CHAPTER 24 Creating and Managing Tables Manufacturer varchar(50) NOT NULL, PrinterDescription varchar(250) NULL ) The CREATE TABLE statement in Listing 24.2 specifies the table to create, followed by an ordered list of columns to add to the table. The following section describes the specifics related to defining the columns. TIP SSMS provides several methods for generating the T-SQL code to create tables. Therefore, you rarely need to type the CREATE TABLE statements from scratch. Instead, you can use the friendly graphical user interface (GUI) screens that enable you to define the table, and then you can generate the T-SQL script. For example, you can right-click a new table in the database diagram and select Generate Change Script to generate the associated T-SQL for the table. One of the important considerations during table creation is schema assignment. Schemas allow you to logically group objects (including tables) and define ownership, independent of the individual users in the database. Schema enhancements introduced in SQL Server 2005 are still available in SQL Server 2008 and can play a significant role in the definition of tables in a database. Consider, for example, the AdventureWorks2008 database that ships with SQL Server 2008. The tables in this database have been assigned to schemas that group the tables according to their functional areas. The schemas in the AdventureWorks2008 database include Sales, Purchasing, Person, Production, HumanResources, and dbo. Some sample tables in the Person schema include the Person and Address tables. The Purchasing schema includes tables that relate to purchasing, including the PurchaseOrderHeader and Vendor tables. The designation of a schema in the CREATE TABLE statement is relatively simple. Listing 24.3 includes a three-part table name for the creation of a Printer table in the HumanResources schema. The database name (AdventureWorks2008) is the first part of the name, followed by a schema name (HumanResources). The last part of Listing 24.3 shows a sample SELECT statement against the Printer table that is owned by the HumanResources schema. The schema name must precede the table, when referenced. The only exception to this rule is tables that belong to the default schema assigned to the user executing the query. LISTING 24.3 Using T-SQL CREATE TABLE in a Schema CREATE TABLE AdventureWorks2008.HumanResources.Printer ( PrinterID int NOT NULL, DepartmentID smallint NOT NULL, PrinterName varchar(50) NOT NULL, Download from www.wowebook.com ptg 747 Defining Columns 24 Manufacturer varchar(50) NOT NULL, PrinterDescription varchar(250) NULL ) go select * from HumanResources.Printer The creation of schemas and assignment of tables to schemas requires some forethought. This task, which is permission oriented, is discussed in more detail in Chapter 11, “Security and User Administration.” Defining Columns A table is defined as a collection of columns. Each column represents an attribute of the database table and has characteristics that define its scope and the type of data it can contain. In defining a column, you must assign a name and a data type. For consistency and readability, the column names should adhere to a naming convention that you define for your environment. Naming conventions often use a set of standard suffixes that indi- cate the type of data the column will contain. For example, you can add the Date suffix to a column name (for example, OrderDate) to identify it as a column that contains date/time data, or you can add the suffix ID (for example, PrinterID) to indicate that the column contains a unique identifier. When creating and naming columns, you need to keep the following restrictions in mind: . You can define up to 1,024 columns (nonsparse + computed) for each table. This number is increased to 30,000 columns if the table has a defined column set using sparse columns. . Column names must be unique within a table. . A row can hold a maximum of 8,060 bytes. Some data types can be stored off the 8KB data page to allow a row to exceed this limit. . A data type must be assigned to each column. These restrictions provide a framework for a column definition. The next consideration in defining a column is the data type. The following section discusses the various data types. Data Types SQL Server 2008 has an extensive list of data types to choose from, including some that are new to SQL Server 2008. New data types include date, time, datetime2, datetimeoffset, filestream, and geometry. Each data type is geared toward a specific type of data that will be stored in the column. Table 24.1 provides a complete list of the data types available in SQL Server 2008. Download from www.wowebook.com ptg 748 CHAPTER 24 Creating and Managing Tables TABLE 24.1 Table Data Types Data Type Range/Description Storage bigint –2 63 (–9,223,372,036,854,775,808) to 2 63-1 (9,223,372,036,854,775,807) 8 bytes binary (n) Binary data with a length of n bytes The number of bytes defined by n, up to 8,000 bit An integer data type that can take a value of 1, 0, or NULL 1 byte for every eight columns that are defined as bits on the table char Up to 8,000 characters 1 byte per character date 0001-01-01 through 9999-12-31 3 bytes datetime through 8 bytes; accurate to December 31, 9999 January 1, 1753, 3.33 milliseconds datetime2 through 8 bytes; accurate to December 31, 9999 January 1, 0001, 100 nanoseconds datetimeoffset through 10 bytes December 31, a time zone offset January 1, 0001, 9999; includes decimal Based on the precision –10 38+1 to 10 38-1 float –1.79E + 38 to –2.23E – 38, 0 and 2.23E – 38 to 1.79E + 38 4 or 8 bytes, depending on the allocation mantissa geography representing round-earth data such as GPS latitude and longitude coordi- nates .NET CLR data type geometry CLR data type repre- senting data in a Euclidean (flat) coordi- nate system .NET hierarchyid levels Up to 892 bytes User defined nodes and image Variable-length binary data Up to 2 31-1 (2,147,483,647) bytes int –2 31 (–2,147,483,648) to 2 31-1 (2,147,483,647) 4 bytes Download from www.wowebook.com ptg 749 Defining Columns 24 TABLE 24.1 Table Data Types Data Type Range/Description Storage money –922,337,203,685,477.5808 to 922,337,203,685,477.5807 8 bytes nchar Up to 4,000 Unicode characters Two times the number of characters entered ntext Up to 2 30-1 (1,073,741,823) characters Two times the number of characters entered numeric (p,s) 10 38-1 Based on the precision –10 38+1 through nvarchar(n) Up to 4,000 Unicode charac- ters Two times the number of characters entered nvarchar(max) Unicode characters up to the maximum storage capacity of Two times the number plus 2 bytes, up to 2 30-1 real –1.18E – 38, 0 and 1.18E – 38 to 3.40E + 38 4 bytes smalldatetime January 1, 1900, through June 6, 2079 4 bytes; accu- rate to 1 minute smallint to 2 15-1 (32,767) 2 bytes –2 15 (–32,768) smallmoney 214,748.3647 4 bytes –214,748.3648 to sql_variant values of Up to 8,016 bytes various SQL Server 2008–supported data types, except text, ntext, image, timestamp, and sql_variant A data type that stores text Up to 231-1 2,147,483,647) characters Up to 2,147,483,647 bytes time 00:00:00.0000000 to 23:59:59.9999999 5 bytes timestamp/rowversion gener- ated, unique binary numbers within a database; generally used for version stamping rows Automatically 8 bytes Download from www.wowebook.com ptg 750 The data type you select is important because it provides scope for the column. For example, if you define a column as type int, you can be assured that only integer data will be stored in the column and that character data will not be allowed. The advantages of data typing are fairly obvious but sometimes overlooked. You should avoid defining most of your columns with a single data type, such as varchar. As mentioned earlier in this chapter, the visual tools provide a great way for you to select a data type: you simply select a data type from a drop-down selection box that lists the available data types. TIP The Object Explorer has a categorized list of all the system data types. To get to it, you open the Programmability node under your database and then expand the Types node. You then see a node named System Data Types that lists all the data type cat- egories, including Exact Numbers, Approximate Numbers, and Date and Time. The data types for each category are listed under each category node. If you mouse over the particular data type, you see a brief description, including the valid range of values. Several data types in SQL Server 2008 deserve special attention. Some of these data types are new to SQL Server 2008 and some of them were introduced in SQL Server 2005. The following sections discuss these data types. CHAPTER 24 Creating and Managing Tables TABLE 24.1 Table Data Types Data Type Range/Description Storage tinyint 0 to 255 1 byte uniqueidentifier unique identifier 16 bytes (GUID) A 16-byte globally varbinary(n) Binary data with a length of n bytes The number of bytes defined by n, up to 8,000 varbinary(max) Binary data up to the maximum storage capacity Two times the number of characters entered plus 2 bytes, up to 2 30-1 varchar (n) 1 byte per character Up to 8,000 characters varchar (max) Non-Unicode characters up to the maximum storage capacity 1 byte per character; maximum 2 31-1 bytes xml XML instances or a variable of XML type 2GB Download from www.wowebook.com ptg 751 Defining Columns 24 New Date/Time Data Types Several new date/time data types were added in SQL Server 2008. These data types were added to enhance SQL Server’s date/time capabilities. The date and time data types were added to separate these two date/time components. The date data type contains only the month, day, and year components, whereas the time data type contains only the time components. The separation of date and time was planned for SQL Server 2005 but never made it to the final release. The precision and scale of date/time data types has been expanded in SQL Server 2008 as well. The datetime2 data type is similar to the datetime data type, but it has a larger range of dates (January 1, 0001, through December 31, 9999), and the time portion of this data type contains fractional seconds with seven digits of precision. The datetime data type is accurate only to within 3 milliseconds, whereas the new datetime2 data type is accurate to 100 nanoseconds. Finally, SQL Server introduces time zone support in a new data type named datetimeoffset. This data type has precision in fractional seconds (like datetime2), but it also contains an extra date/time component that defines the time zone offset for the date. The time zone offset is two digits that represent the offset hours and two digits that repre- sent the offset minutes. The offset is used against the UTC date. The following example shows how this new data type can be used: select CAST(‘2009-07-08 11:33:22.1234567-04:00’ AS datetimeoffset(7)) The xml Data Type The xml data type (introduced in SQL Server 2005) enables you to store XML documents and XML fragments in a SQL Server database. (An XML fragment is an XML instance that is missing a single top-level element.) Use of the xml data type is discussed in more detail in Chapter 47, “Using XML in SQL Server 2008.” The hierarchyid Data Type The hierarchyid data type is new in SQL Server 2008. The hierarchyid data type is a vari- able-length system data type used to represent a position in a tree hierarchy. A column of type hierarchyid does not automatically represent a tree. It is up to the application to generate and assign hierarchyid values in such a way that the desired relationship between rows is reflected in the values. For more information and examples for using the hierarchyid data type, see Chapter 42, “What’s New for Transact-SQL in SQL Server 2008.” Spatial Data Types SQL Server 2008 introduces support for storing geographical data with the inclusion of new spatial data types. Spatial data types provide a comprehensive, high-performance, and extensible data storage solution for spatial data, enabling organizations of any scale to integrate geospatial features into their applications and services. Spatial data types can be used to store and manipulate location-based information and come in the form of two new data types: geography and geometry. The geography data type is a .NET CLR data type that provides a storage structure for geodetic data, sometimes Download from www.wowebook.com ptg 752 referred to as round earth data because it assumes a roughly spherical model of the world. It provides a storage structure for spatial data that is defined by latitude and longitude coordinates using an industry standard ellipsoid such as WGS84, the projection method used by Global Positioning System (GPS) applications. The geometry data type is a .NET CLR data type that supports the planar model/data, which assumes a flat projection and is therefore sometimes called flat earth. geometry data is represented as points, lines, and polygons on a flat surface, such as maps and interior floor plans where the curvature of the earth does not need to be taken into account. For more information on and examples using spatial data types, see Chapter 42. Large-Value Data Types Three large-value data types added in SQL Server 2005 allow you to store a significant amount of data in a single column. They allow you to store up to 2 31 bytes of non- Unicode data and 2 30 bytes of Unicode data. All these data types have the (max) designa- tor: varchar(max), nvarchar(max), and varbinary(max). The varchar, nvarchar, and varbinary data types were available prior to SQL Server 2005, but the max parameter gave these types additional scope. The great thing about these data types is that they are much easier to work with than large object (LOB) data types. LOB data types (which include text, ntext, and image) require special programming when retrieving and storing data. The large-value data types do not have these restrictions. They can be used much like their smaller counterparts varchar(n), nvarchar(n), and varbinary(n) that are defined without the max keyword. So if you want to select data from a varchar(max) column, you can simply execute a SELECT statement against it, regardless of the amount of data stored in it. Consider, for example, the following SELECT statement, executed against a varchar(max) column named DocumentSummary in the AdventureWorks2008.Production.Document table: select Title, substring(DocumentSummary,1,30) ‘DocumentSummary’ from production.document where LEFT(DocumentSummary,30) like ‘Reflector%’ /* results from previous select statement Title DocumentSummary Front Reflector Bracket Installation Reflectors are vital safety co */ This works fine with the varchar(max) column, but the LEFT function used in the WHERE clause would cause an error if the column were a text column instead. The large-value data types can be stored in the data row or in a separate data page, based on the setting of the sp_tableoption ‘large value types out of row’ option. If the option is set to OFF, up to 8,000 characters can be stored in this column in the actual data row. If the option is set to ON, data for this column is stored in a separate data page if its length would result in the data row exceeding 8,060 bytes. The actual location of the column data is transparent to any user accessing the table. CHAPTER 24 Creating and Managing Tables Download from www.wowebook.com ptg 753 Defining Columns 24 Large Row Support In SQL Server 2000, there was a strict limit of 8,060 bytes that could be stored in a single row. If the total amount of data exceeded this limit, the update or insert would fail. Enhancements were made in SQL Server 2005 to dynamically manage rows that exceed the 8,060-byte limit. This dynamic behavior is designed for columns that are defined as varchar, nvarchar, varbinary, or sql_variant. If the values in these columns cause the total size of the row to go beyond the 8,060-byte limit, SQL Server moves one or more of the variable-length columns to pages in the ROW_OVERFLOW_DATA allocation unit. A pointer to this separate storage location, rather than the actual data, is kept in the data row. If the data row shrinks below the 8,060-byte limit at a later time, SQL Server dynamically moves the data from the ROW_OVERFLOW_DATA allocation unit back into the data page. The following example creates a table that has columns that could exceed the 8,060-byte limit, with a total of 9,000 characters: CREATE TABLE t1 (col1 varchar(4000), col2 varchar(5000)) insert t1 select replicate(‘x’, 4000),replicate(‘x’, 5000) If you execute the CREATE TABLE statement, you do not get any warning message related to the 8,060-byte limit. After the table is created, you can execute an insert into the table that exceeds the 8,060-byte limit. The insert succeeds, and the dynamic allocation previ- ously described is handled automatically. User-Defined Data Types User-defined data types allow you to create custom data types that are based on the exist- ing system data types. These data types are also called alias data types in SQL Server 2008. You create a user-defined data type and give it a unique name that you can then use in the definitions of tables. For example, you can create a user-defined data type named ShortDescription, defined as varchar(20), and assign it to any column. This promotes data type consistency across your tables. You can create user-defined data types by using T-SQL in a couple of different ways. Using the sp_addtype system stored procedure and using the new CREATE TYPE command are two possibilities. The sp_addtype system stored procedure is slated to be removed in a future version of SQL Server, so using the CREATE TYPE command is preferred. The following example shows how to create the ShortDescription user-defined data type: CREATE TYPE [dbo].[ShortDescription] FROM [varchar](20) NOT NULL After a user-defined data type is created, you can use it in the definition of tables. The following is an example of a table created with the new ShortDescription user-defined data type: CREATE TABLE [dbo].CodeTable (TableId int identity, TableDesc ShortDescription) Download from www.wowebook.com . values. Several data types in SQL Server 2008 deserve special attention. Some of these data types are new to SQL Server 2008 and some of them were introduced in SQL Server 2005. The following. the hierarchyid data type, see Chapter 42, “What’s New for Transact -SQL in SQL Server 2008. ” Spatial Data Types SQL Server 2008 introduces support for storing geographical data with the inclusion. introduced in SQL Server 2005 are still available in SQL Server 2008 and can play a significant role in the definition of tables in a database. Consider, for example, the AdventureWorks2008 database

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

TỪ KHÓA LIÊN QUAN