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

Microsoft SQL Server 2008 R2 Unleashed- P93 pptx

10 340 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 864 CHAPTER 27 Creating and Managing Views in SQL Server are searched. The same basic principles apply to indexes on views, but indexed views are best utilized to increase performance in the following scenarios: . Aggregations such as SUM or AVG can be precomputed and stored in the index to minimize the potentially expensive computations during query execution. . Large table joins can be persisted to eliminate the need to write a join when retriev- ing the data. . A combination of aggregations and large table joins can be stored. The performance improvements from the aforementioned scenarios can be significant and can justify the use of an index. The Query Optimizer can use the precomputed results stored in the view’s index and avoid the cost of aggregating or joining the underlying tables. Keep in mind that the Query Optimizer may still use the indexes found on the member tables of the view instead of the index on the view. The Query Optimizer uses the following conditions in determining whether the index on the view can be utilized: . The tables in the query FROM clause must be a superset of the tables in the indexed view’s FROM clause. In other words, the query must contain all the tables in the view. The query can contain additional tables not contained in the view. . The join conditions in the query must be a superset of the view’s join conditions. . The aggregate columns in the query must be derivable from a subset of the aggregate columns in the view. . All expressions in the query SELECT list must be derivable from the view SELECT list or from the tables not included in the view definition. . All columns in the query search condition predicates that belong to tables in the view definition must appear in the GROUP BY list, the SELECT list if there is no GROUP BY, or the same or equivalent predicate in the view definition. NOTE Predicting the Query Optimizer’s use of an indexed view can be complicated and depends on the complexity of the view that is indexed and the complexity of the query that may utilize the view. A detailed discussion of these scenarios is beyond the scope of this chapter, but the Microsoft TechNet article “Improving Performance with SQL Server 2005 Indexed Views” provides that detail. This article includes more than 20 examples that illustrate the use of indexed views and the conditions the Query Optimizer uses in selecting an indexed view. As you can see from the title, this article was written for SQL Server 2005, but the content is still relative for SQL Server 2008. The flip side of performance with indexes (including those on views) is that there is a cost in maintaining an index. This cost can adversely affect the performance of data modifica- tions against objects that have these indexes. Generally speaking, indexes should not be placed on views that have underlying data sets that are frequently updated. Caution must Download from www.wowebook.com ptg 865 Indexed Views 27 be exercised when placing indexes on views that support online transaction processing (OLTP) applications. A balance must be struck between improving the performance of database modification and improving the performance of database inquiry. Indexed views improve database inquiry. Databases used for data warehousing and decision support are usually the best candidates for indexed views. The impact of data modifications on indexed views is exacerbated by the fact that the complete result set of a view is stored in the database. When the clustered index is created on a view, you specify the clustered index key(s) in the CREATE UNIQUE CLUSTERED INDEX statement, but more than the columns in the key are stored in the database. As in a clus- tered index on a base table, the B-tree structure of the clustered index contains only the key columns, but the data rows contain all the columns in the view’s result set. The increased space utilized by the index view is demonstrated in the following examples. This first example creates a view and an associated index view similar to the Adventureworks2008 Production.vProductAndDescription view used in a prior example: result setCREATE VIEW [Production].[vProductAndDescription_2] WITH SCHEMABINDING AS View (indexed or standard) to display products and — product descriptions by language. SELECT p.[ProductID] ,pmx.[CultureID] FROM [Production].[Product] p INNER JOIN [Production].[ProductModel] pm ON p.[ProductModelID] = pm.[ProductModelID] INNER JOIN [Production].[ProductModelProductDescriptionCulture] pmx ON pm.[ProductModelID] = pmx.[ProductModelID] INNER JOIN [Production].[ProductDescription] pd ON pmx.[ProductDescriptionID] = pd.[ProductDescriptionID]; go CREATE UNIQUE CLUSTERED INDEX [IX_vProductAndDescription_2] ON [Production].[vProductAndDescription_2] ( [CultureID] ASC, [ProductID] ASC ) The difference with this new view is that the result set returns only the two columns in the clustered index; there are no additional columns in the result set. When the new view and associated index are created, you can compare the amount of physical storage occupied by each. The following example shows the sp_spaceused commands for each view and the associated results: exec sp_spaceused ‘Production.vProductAndDescription’ Download from www.wowebook.com ptg 866 CHAPTER 27 Creating and Managing Views in SQL Server /* results name rows reserved data index_size unused ——————————— —— ———— ——— ————— ——— vProductAndDescription 1764 592 KB 560 KB 16 KB 16 KB */ exec sp_spaceused ‘Production.vProductAndDescription_2’ /* results name rows reserved data index_size unused ——————————— —— ———— ——— ————— ——— vProductAndDescription_2 1764 64 KB 48 KB 16 KB 0 KB */ Take note of the reserved space and data results for each view. The view that was created with only two result columns takes much less space than the view that has an index with five result columns. You need to consider the overhead of storing these additional result columns along with the index when creating the view and related index. Changes made to any of the columns in the base tables that are part of the view results must also be maintained for the index view as well. Nonclustered indexes can be created on a view, and they can also provide added query performance benefits when used properly. Typically, columns that are not part of the clus- tered index on a view are added to the nonclustered index. Like nonclustered indexes on tables, the nonclustered indexes on the view provide additional options for the Query Optimizer when it is choosing the best query path. Common search arguments and foreign key columns that may be joined in the view are common targets for nonclustered indexes. To Expand or Not to Expand The expansion of a view to its base tables is a key consideration when evaluating the use of indexes on views. The SQL Server Query Optimizer can expand a view to its base tables or decide to utilize indexes that are found on the view itself. The selection of an index on a view is directly related to the edition of SQL Server 2008 you are running and the expan- sion options selected for a related query. As mentioned earlier, the Enterprise and Developer Editions are the only editions that allow the Query Optimizer to use an indexed view to solve queries that structurally match the view, even if they don’t refer to the view by name. For other editions of SQL Server 2008, the view must be referenced in the query, and the NOEXPAND hint must be used as well for the Query Optimizer to consider the index on the view. The following example demonstrates the use of the NOEXPAND hint: SELECT * FROM Production.vProductAndDescription (NOEXPAND) WHERE cultureid = ‘he’ Download from www.wowebook.com ptg 867 Summary 27 When this example is run against the Adventureworks2008 database, the execution plan indicates that a clustered index seek will be performed, using the index on the view. If the NOEXPAND hint is removed from the query, the execution plan will ignore the index on the view and return the results from the base table(s). The only exception to this is when the Enterprise or Developer Edition is used. These editions can always consider indexed views but may or may not choose to use them. SQL Server also has options to force the Query Optimizer to use the expanded base tables and ignore indexed views. The (EXPAND VIEWS) query hint ensures that SQL Server will process a query by accessing data directly from the base tables. This option might seem counterproductive, but it can be useful in situations in which contention exists on an indexed view. It is also handy for testing indexed views and determining overall perfor- mance with and without the use of indexed views. The following example, which utilizes the same view as the previous example, demon- strates the use of the (EXPAND VIEWS) query hint: SELECT * FROM Production.vProductAndDescription WHERE cultureid = ‘he’ OPTION (EXPAND VIEWS) The query plan in this example shows the use of the base tables, and the index on the view is ignored. For more information on query optimization and indexes, see Chapter 34. Summary Views provide a broad spectrum of functionality, ranging from simple organization to improved overall query performance. They can simplify life for developers and users by filtering the complexity of a database. They can help organize data access and provide a security mechanism that helps keep a database safe. Finally, they can provide performance improvements via the use of partitioned views and indexed views that help keep your database fast. Some of the same benefits, including performance and security benefits, can also be achieved through the use of stored procedures. Chapter 28, “Creating and Managing Stored Procedures,” delves into these useful and powerful database objects. Download from www.wowebook.com ptg This page intentionally left blank Download from www.wowebook.com ptg CHAPTER 28 Creating and Managing Stored Procedures IN THIS CHAPTER . 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 A stored procedure is one or more SQL commands stored in a database as an executable object. Stored procedures can be called interactively, from within client application code, from within other stored procedures, and from within trig- gers. Parameters can be passed to and returned from stored procedures to increase their usefulness and flexibility. A stored procedure can also return a number of result sets and a status code. What’s New in Creating and Managing Stored Procedures Unlike SQL Server 2005 with its addition of .NET CLR stored procedures, SQL Server 2008 doesn’t introduce any significant changes to the creation and functionality of stored procedures. However, one of the most welcome enhancements is the return of the Transact-SQL (T-SQL) debugger to SQL Server Management Studio (SSMS). System administrators can now debug stored procedures without having to install Visual Studio (VS). An introduction to debugging stored procedures is provided later in this chapter in the section “Debugging Stored Procedures Using SQL Server Management Studio.” One small enhancement to the functionality of stored procedures in SQL Server 2008 is the capability to use table- valued parameters. Table-valued parameters allow you to pass table variables as input parameters to stored procedures so that the contents may be accessed from within the stored procedure. In previous versions of SQL Server, it was not possible to access the contents of table variables outside Download from www.wowebook.com ptg 870 CHAPTER 28 Creating and Managing Stored Procedures the scope in which they were declared. The “Using Table-Valued Parameters” section in this chapter provides a description and examples on how to make use of this new feature. One other enhancement in SQL Server 2008 is that there is no longer a maximum size for your stored procedure source code. Advantages of Stored Procedures Using stored procedures provides many advantages over executing large and complex SQL batches from client applications. Following are some of them: . Modular programming—Subroutines and functions are often used in ordinary 3GL and 4GL languages (such as C, C++, and Microsoft Visual Basic) to break code into smaller, more manageable pieces. The same advantages are achieved when using stored procedures, with the difference that the stored procedure is stored in SQL Server and can be called by any client application. . Restricted, function-based access to tables—A user can have permission to execute a stored procedure without having permissions to operate directly on the underlying tables. . Reduced network traffic—Stored procedures can consist of many individual SQL statements but can be executed with a single statement. This allows you to reduce the number and size of calls from the client to the server. . Faster execution—Stored procedures’ query plans are kept in memory after the first execution. The code doesn’t have to be reparsed and reoptimized on subsequent executions. . Enforced consistency—If users modify data only through stored procedures, prob- lems that often result from ad hoc modifications (such as omitting a crucial WHERE clause) are eliminated. . Reduced operator and programmer errors—Because less information is being passed, complex tasks can be executed more easily, with less likelihood of SQL errors. . Automating complex or sensitive transactions—If all modifications of certain tables take place in stored procedures, you can guarantee the data integrity on those tables. Some of the disadvantages of using stored procedures (depending on the environment) are as follows: . Increase in server processing requirements—Using stored procedures can increase the amount of processing that takes place on the server. In a large user envi- ronment with considerable activity in the server, it may be more desirable to offload some of the processing to the client workstation. . Less cross-DBMS portability—Although the ANSI-99 SQL standard provides a standard for stored procedures in database management systems (DBMSs), the for- mat and structure are different from those of SQL Server stored procedures. These Download from www.wowebook.com ptg 871 Creating Stored Procedures procedures would all have to be rewritten to be compatible with another DBMS environment. Should you use stored procedures? The answer is (as it often is), it depends. If you are working in a two-tier environment, using stored procedures is often advanta- geous. The trend is shifting to three- (or more) tier environments. In such environments, business logic is often handled in some middle tier (possibly ActiveX objects managed by Microsoft Transaction Server). If you operate in that type of environment, you might want to restrict the stored procedures to performing basic data-related tasks, such as retrievals, insertions, updates, and deletions. NOTE You can use s tored procedures to make a database sor t of a “black box” as far as the developers and the application code are concerned. If all database access is managed through stored procedures, the applications are shielded from possible changes to the underlying database structures. For example, one organization found the need to split one table across multiple data- bases. By simply modifying the existing stored procedures to handle the multiple tables and by using distributed partitioned views, the company was able to make this change without requiring any changes to the front-end application code. Creating Stored Procedures To create a stored procedure, you need to give the procedure a unique name within the schema and then write the sequence of SQL statements to be executed within the proce- dure. Following is the basic syntax for creating stored procedures: CREATE { PROC | PROCEDURE } [schema_name.]procedure_name [ ; number ] [ { @parameter [ schema_name.]data_type } [ VARYING ] [ = default ] [ OUT | OUTPUT ] [READONLY] ] [ , n ] [ WITH { [ ENCRYPTION ] , [ RECOMPILE ] , [ EXECUTE_AS_Clause ] [ , n] ] [ FOR REPLICATION ] AS [BEGIN] SQL_Statements [ RETURN scalar_expression ] [END] It is good programming practice to always end a procedure with the RETURN statement and to specify a return status other than 0 when an error condition occurs. Listing 28.1 shows 28 Download from www.wowebook.com ptg 872 CHAPTER 28 Creating and Managing Stored Procedures a simple stored procedure that returns book titles and the names of the authors who wrote them. LISTING 28.1 A Sample Stored Procedure use bigpubs2008 go IF EXISTS ( SELECT * FROM sys.procedures WHERE schema_id = schema_id(‘dbo’) AND name = N’title_authors’) DROP PROCEDURE dbo.title_authors GO CREATE PROCEDURE title_authors AS BEGIN SELECT a.au_lname, a.au_fname, t.title FROM titles t INNER JOIN titleauthor ta ON t.title_id = ta.title_id RIGHT OUTER JOIN authors a ON ta.au_id = a.au_id RETURN 0 END NOTE Unless stated otherwise, all examples in this chapter run in the context of the bigpubs2008 database. Creating Procedures in SSMS To create a stored procedure in SSMS, open the object tree for the database in which you want to create the procedure, open the Programmability folder, right-click the Stored Procedures folder, and from the context menu, choose New Stored Procedure. SSMS opens a new query window, populated with code that is based on a default template for stored procedures. Listing 28.2 shows an example of the default template code for a stored proce- dure that would be opened into a new query window. LISTING 28.2 An Example of a New Stored Procedure Creation Script Generated by SSMS ================================================ Template generated from Template Explorer using: Create Procedure (New Menu).SQL Use the Specify Values for Template Parameters command (Ctrl-Shift-M) to fill in the parameter values below. Download from www.wowebook.com ptg 873 Creating Stored Procedures This block of comments will not be included in the definition of the procedure. ================================================ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO ============================================= Author: <Author,,Name> Create date: <Create Date,,> Description: <Description,,> ============================================= CREATE PROCEDURE <Procedure_Name, sysname, ProcedureName> - Add the parameters for the stored procedure here <@Param1, sysname, @p1> <Datatype_For_Param1, , int> = <Default_Value_For_Param1, , 0>, <@Param2, sysname, @p2> <Datatype_For_Param2, , int> = <Default_Value_For_Param2, , 0> AS BEGIN - SET NOCOUNT ON added to prevent extra result sets from - interfering with SELECT statements. SET NOCOUNT ON; Insert statements for procedure here SELECT <@Param1, sysname, @p1>, <@Param2, sysname, @p2> END GO You can modify the template code as necessary to set the procedure name and to specify the parameters, return value, and procedure body. When you are finished, you can execute the contents of the query window to create the procedure. After you have created the procedure successfully, it is recommended that you save the source code to a file by choosing the Save or Save As option from the File menu. This way, you can re-create the stored procedure from the file if it is accidentally dropped from the database. TIP When you create a new stored procedure in SSMS, the procedure does not show up in the Stored Procedures folder in the Object Browser unless you right-click the Stored Procedures folder and choose the Refresh option. 28 Download from www.wowebook.com . view. As you can see from the title, this article was written for SQL Server 2005, but the content is still relative for SQL Server 2008. The flip side of performance with indexes (including those. code. What’s New in Creating and Managing Stored Procedures Unlike SQL Server 2005 with its addition of .NET CLR stored procedures, SQL Server 2008 doesn’t introduce any significant changes to the creation. section “Debugging Stored Procedures Using SQL Server Management Studio.” One small enhancement to the functionality of stored procedures in SQL Server 2008 is the capability to use table- valued

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

TỪ KHÓA LIÊN QUAN