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

Microsoft SQL Server 2008 R2 Unleashed- P198 ppt

10 83 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 1964 CHAPTER 49 SQL Server Service Broker Designing a Sample System The sample messaging system used in this chapter has the following design: an update stored procedure in AdventureWorks2008.Production.ProductModel starts up a service that initiates a conversation with a service in XCatMgmt. It does this by sending a message to the inbound work queue of XCatMgmt. When the transaction surrounding the initial send is complete, Service Broker transmits the message, signaling that a catalog change for an AdventureWorks Cycles product model is ready for processing. In response to the arrival of this new message, Service Broker executes a stored procedure associated with a catalog maintenance service for XCatMgmt, known as its service program. This process is known as internal activation; it is internal because the stored procedure resides in and is activated by SQL Server. Because a Service Broker program might not always be a stored procedure, external activa- tion is also available when you use event notification with the QUEUE_ACTIVATION event. You can create an event notification service and map it to your Service Broker service and queue by using syntax such as the following: CREATE QUEUE NotificationQueue GO CREATE SERVICE EventNotificationService ON QUEUE NotificationQueue ([http://schemas.microsoft.com/SQL/Notifications/PostEventNotification]) GO CREATE EVENT NOTIFICATION NotifyMe ON QUEUE NotificationQueue FOR QUEUE_ACTIVATION TO SERVICE ‘EventNotificationService’, ‘broker-instance-guid’ Note that you need to retrieve your database’s Service Broker unique identifier and replace ’broker-instance-guid’ with it for the example to work. To do this, you run the following query: SELECT service_broker_guid FROM sys.databases WHERE NAME = ‘AdventureWorks2008’ go service_broker_guid 3036906E-8B9E-4266-A8C6-DD4E01B656CA (1 row(s) affected) You should keep this query in mind because you need it later in this chapter when you’re working on service conversations. Let’s return to the sample system’s description. When the catalog maintenance service’s work is done, it sends an acknowledgment message back to the sender’s inbound queue. ptg 1965 Understanding Service Broker Constructs 49 Service Broker Application Conversion Group Dialog (Conversion) Service Queues Queues Program Program Messages Contract Activation Activation Service FIGURE 49.1 Service Broker concepts illustrated. To accomplish everything included in the design so far, you need to represent the follow- ing kinds of objects in the system: . Two types of messages: one defining product model catalog changes and one for acknowledgments . Two queues, one for each service . One contract that defines the message flow between the services . Two services, each representing an endpoint in the system . At least one conversation and its related conversation group The following sections describe how to define and build on all these new constructs, and you learn how they work together in the orchestration of Service Broker applications. Understanding Service Broker Constructs To introduce the new Service Broker constructs you’ll be using, Figure 49.1 shows the interrelations between the constructs described in the upcoming subsections. Figure 49.1 illustrates the fact that a dialog is a conversation between two services. These services exchange typed (or untyped) messages by sending them to queues according to the rules of a contract. Each service can have a service program activated by Service Broker to receive messages from a queue. Every conversation belongs to a conversation group. Messages are always sent with respect to a conversation group. One or more conversation groups make up a Service Broker application. Defining Messages and Choosing a Message Type For the AdventureWorks2008 database to communicate with the XCatMgmt database via Service Broker, a dialog between two services must take place. Within this conversation, each service sends messages to or receives messages from queues, providing the indirection needed for the underlying systems to stay loosely coupled. ptg 1966 CHAPTER 49 SQL Server Service Broker The dialog messages are typed to constrain and (optionally) validate their content. You use the new SQL Server database object MESSAGE to represent a typed message. Defining the messages to be transmitted is the first step in building a Service Broker application. You create SQL Server messages by using the following syntax: CREATE MESSAGE TYPE [ AUTHORIZATION UserName ] [ VALIDATION = { NONE | EMPTY | WELL_FORMED_XML | VALID_XML WITH SCHEMA COLLECTION XMLSchemaCollectionName } ] You can alter message types by using the intuitive ALTER MESSAGE TYPE syntax. Before you create the first message type, you need to create a Windows user on the local server and associate a SQL Server login with it, giving it db_owner permissions in both AdventureWorks2008 and XCatMgmt. You need to specify this user in the AUTHORIZATION clause of any object you create that includes this clause. In the examples in this chapter, this is exemplified as SSBTestUserName. Messages can be validated based on the following options: . NONE—Do no validation; any message content is acceptable. . EMPTY—Transmitted messages must be empty. . WELL_FORMED_XML—Transmitted messages must be any well-formed XML. . VALID_XML WITH SCHEMA COLLECTION—Transmitted messages must be valid XML cor- responding to any schema in the XML schema collection specified in XMLSchemaCollectionName. It is highly recommended that applications use either WELL_FORMED_XML or VALID_XML WITH SCHEMA COLLECTION. You don’t want just any old message structure coming across the pipe because your application will almost certainly be looking for specific values in a specific location. XML is appropriate because it is the ubiquitous standard today. Note that the XML content of messages is actually stored as varbinary(MAX). (XML schema collec- tions are covered in the section “Using XML Schema Collections” in Chapter 47, “Using XML in SQL Server 2008.”) Now you should go ahead and create your two message types, both of which should be set to VALID_XML. The first deals with catalog entries and/or changes (that is, updates and deletions), and the second is a generic message type you use for all acknowledgments. Listing 49.2 shows the schemas for these message types, along with the necessary schema collection and message type creation syntax. LISTING 49.2 DDL for Creating the Sample Message Types and Their Associated XML Schema Collections Note: Execute the T-SQL below, and then change the USE statement to ‘USE AdventureWorks2008’ and execute it again. ptg 1967 Understanding Service Broker Constructs 49 USE XCatMgmt GO CREATE XML SCHEMA COLLECTION CatalogChangeSchema AS ‘<?xml version=”1.0”?> <xs:schema targetNamespace=”urn:www-samspublishing-com:examples:ssb:catalogchange” elementFormDefault=”qualified” xmlns=”urn:www-samspublishing-com:examples:ssb:catalogchange” xmlns:xs=”http://www.w3.org/2001/XMLSchema”> <xs:element name=”CatalogChangeMessage”> <xs:complexType> <xs:sequence maxOccurs=”unbounded”> <xs:element name=”CatalogChange” type=”CatalogChangeType”/> </xs:sequence> </xs:complexType> </xs:element> <xs:complexType name=”CatalogChangeType”> <xs:sequence> <xs:element name=”Summary” type=”xs:string”/> <xs:element name=”Features” type=”xs:string” minOccurs=”0”/> <xs:element name=”Specifications” type=”xs:string” minOccurs=”0”/> </xs:sequence> <xs:attribute name=”SourceProductId” type=”xs:integer” use=”required”/> <xs:attribute name=”ManufacturerId” type=”xs:integer” use=”required”/> <xs:attribute name=”ChangeType”> <xs:simpleType> <xs:restriction base=”xs:integer”> <xs:enumeration id=”Insert” value=”1”/> <xs:enumeration id=”Update” value=”2”/> <xs:enumeration id=”Delete” value=”3”/> </xs:restriction> </xs:simpleType> </xs:attribute> <xs:attribute name=”Price” type=”xs:decimal”/> <xs:attribute name=”Name” type=”xs:string”/> </xs:complexType> </xs:schema>’ GO CREATE MESSAGE TYPE [//samspublishing.com/SS2008/SSB/MessageTypes/CatalogChangeMessage] AUTHORIZATION [SSBTestUserName] VALIDATION = VALID_XML WITH SCHEMA COLLECTION CatalogChangeSchema ptg 1968 CHAPTER 49 SQL Server Service Broker GO CREATE XML SCHEMA COLLECTION GenericAcknowledgementSchema AS ‘<?xml version=”1.0” encoding=”utf-8” ?> <xs:schema targetNamespace=”urn:www-samspublishing-com:examples:ssb:genericack” elementFormDefault=”qualified” xmlns=”urn:www-samspublishing-com:examples:ssb:genericack” xmlns:xs=”http://www.w3.org/2001/XMLSchema”> <xs:simpleType name=”MsgTypeType”> <xs:restriction base=”xs:integer”> <xs:enumeration id=”SuccessMsg” value=”0”/> <xs:enumeration id=”FailureMsg” value=”1”/> <xs:enumeration id=”WarningMsg” value=”2”/> </xs:restriction> </xs:simpleType> <xs:element name=”Ack”> <xs:complexType> <xs:sequence> <xs:element name=”ResultMessage”> <xs:complexType mixed=”true”> <xs:attribute name=”ContentId” type=”xs:integer” use=”optional”/> <xs:attribute name=”MsgType” type=”MsgTypeType”/> </xs:complexType> </xs:element> </xs:sequence> <xs:attribute name=”ResultCode”> <xs:simpleType> <xs:restriction base=”xs:integer”> <xs:enumeration id=”Success” value=”1”/> <xs:enumeration id=”Failure” value=”0”/> </xs:restriction> </xs:simpleType> </xs:attribute> </xs:complexType> </xs:element> </xs:schema>’ GO CREATE MESSAGE TYPE ptg 1969 Understanding Service Broker Constructs 49 [//samspublishing.com/SS2008/SSB/MessageTypes/GenericAck] AUTHORIZATION [SSBTestUserName] VALIDATION = VALID_XML WITH SCHEMA COLLECTION GenericAcknowledgementSchema Note that the message types and schema collections should be created (as the Listing 49.2 comment indicates) in both participating databases, AdventureWorks2008 and XCatMgmt. The reason is that when you create the XML messages, you might want to temporarily store them as local typed XML variables to ensure that they are validated before being sent. However, it is only necessary to create the schema collections on the database where the message will be received because the receiving instance of Service Broker performs the validation. In the MESSAGE TYPE DDL, you should use this standard naming convention for Service Broker objects: //DomainName/Path/ObjectType/ObjectName. This convention will help you identify your objects later. (Don’t worry if the name is long; you can use Object Explorer’s drag-and-drop feature to drag the name into your scripts.) If you’re curious, you can view the newly created objects in Object Explorer by selecting the Service Broker node and then expanding the Message Types node. You can find the XML schema collec- tions by selecting the Programmability node and then selecting the Types node and expanding the XML Schema Collections node. Note that there are several built-in message types that any queue can receive from Service Broker. Service programs should be built to handle these as well as the specific message types defined in their contracts. You can view them all in the Object Brower (they all begin with http://schemas.microsoft.com/SQL/ServiceBroker/). When receiving messages from a queue, you should filter them based on the message_type_name column of the queue to be sure you handle each one correctly. You can expect to see these types in your queues: . Error—This type is enqueued by Service Broker whenever an error is encountered. Alternatively, a user program can choose to create these types. . EndDialog—This type is enqueued by Service Broker when a conversation ends in response to calls to END CONVERSATION (as explained later in this chapter). Service programs can also send messages of the built-in type DialogTimer. Service Broker delivers these messages to the specified queue when a specific time period has elapsed. To tell Service Broker to send a DialogTimer message to the queue associated with a service after 5 minutes has elapsed, for example, you execute the following T-SQL during a conversation in the service program: BEGIN CONVERSATION TIMER (@ConversationHandle) TIMEOUT = 600 In this code, you replace @ConversationHandle with the unique identifier assigned to your conversation (as explained later in this chapter). Now that all your message types are in place and you know which built-in messages to expect, you can create the contract that defines the message flow in this system. ptg 1970 CHAPTER 49 SQL Server Service Broker Setting Up Contracts for Communication You use contracts to specify which messages can flow from which endpoints to which queues. Two new T-SQL keywords come into play here: . INITIATOR—This service begins a messaging conversion. . TARGET—This service engages in (or accepts) conversions with an initiator. As described earlier, the sample system is initiated by a stored procedure in AdventureWorks2008 that sends a message of type CatalogChangeMessage to a queue in XCatMgmt. Every CatalogChangeMessage is thus sent by a conversation initiator. The catalog management service that receives these messages sends an acknowledgment reply message of type GeneralAck when it completes the requested change. GeneralAck messages in this case are thus sent by the target of the original initiated message. To create the contract that represents this message flow, you need to execute the following code in both databases: Note: Change SSBTestUserName to a user on your system, and run this code on both AdventureWorks2008 and XCatMgmt CREATE CONTRACT [//samspublishing.com/SS2008/SSB/Contracts/BasicCatalogChangeContract] AUTHORIZATION [SSBTestUserName] ( [//samspublishing.com/SS2008/SSB/MessageTypes/CatalogChangeMessage] SENT BY INITIATOR, [//samspublishing.com/SS2008/SSB/MessageTypes/GenericAck] SENT BY TARGET ) This code for creating contracts also allows for message types to be sent by either the initiator or the target, in which case, you need to specify SENT BY ANY. A service can also be bound to more than one contract. Note that there is also a built-in contract called DEFAULT (as well as a message type of DEFAULT) that you use during conversations that do not specify a contract. Contracts cannot be altered because only DROP CONTRACT exists. Now that your contract and message types are ready, the next step is to create the queues needed to store the messages. Creating Queues for Message Storage Queues represent a layer of communication indirection between services, allowing them to send and receive messages independently of each other. A queue is a first-class database object, internally implemented as a table that has some unique behaviors. ptg 1971 Understanding Service Broker Constructs 49 NOTE You can select values from any queue by using standard syntax, such as SELECT * FROM QueueName WITH (NOLOCK) . This has no effect on the data in the queue, nor does it imply a message receive operation. It does, however, cause blocking on the internal queue table, so you should always use the NOLOCK hint. Data Manipulation Language (DML) statements on queues are not permitted. The following is the syntax for creating a queue: CREATE QUEUE DatabaseName.SchemaName.QueueName [ WITH [ STATUS = { ON | OFF } [ , ] ] [ RETENTION = { ON | OFF } [ , ] ] [ ACTIVATION ( [ STATUS = { ON | OFF }, ] PROCEDURE_NAME = SPName, MAX_QUEUE_READERS = Number, EXECUTE AS { SELF | ‘UserName’ | OWNER } )] ] [ ON { filegroup | [ DEFAULT ] } ] This syntax contains the following options: . STATUS—This option turns the queue on or off, meaning that it may or may not be used. (This capability is useful with ALTER QUEUE when a queue must be temporarily put offline.) It defaults to ON. . RETENTION—This option turns message retention on or off during active conversations that use the queue. It defaults to OFF. You might need to turn this feature on at some point if you need to see messages that have already been processed. The reason is that the normal message receive operation implicitly deletes a message when the transac- tion that surrounds it commits. When RETENTION is set to ON, the value in the status column for the queue is changed to 1 after a receive instead of a deletion. In addition, sent messages are copied to the sender’s queue (duplicated) and given a status value of 3, to fully audit the message flow in both directions. . ACTIVATION—This clause is used to specify the following options regarding the inter- nally activated stored procedure (described earlier): . STATUS—This option is used to turn activation on or off. (You may want to temporarily turn off activation when updating a procedure.) It defaults to ON. . PROCEDURE_NAME—This option specifies the name of the activated procedure. ptg 1972 CHAPTER 49 SQL Server Service Broker . MAX_QUEUE_READERS—This option supplies an integer that indicates to Service Broker the maximum number of instances of the activated procedure to create. This setting hints at the fact that Service Broker uses multithreading to instan- tiate additional queue readers when unread messages in the queue build up faster than the existing instances can process them. This is a great boon to developers because they no longer have to develop and maintain the multi- threaded code to perform this task. To do this, Service Broker internally creates queue monitors that keep an eye on the number of unread messages in the queue. Keep this number the same as the number of processor cores you have in your system. . EXECUTE AS—This option specifies the name of the user under which the initi- ated procedure runs. You need two queues for the application so far: one used by each service. The T-SQL in Listing 49.3 creates them. LISTING 49.3 T-SQL for Creating Queues and Their Activated Stored Procedures USE XCatMgmt GO CREATE PROC Publication.CatalogChangeQueueReader AS GO CREATE QUEUE Publication.CatalogChangeQueue WITH STATUS = ON, ACTIVATION ( STATUS = ON, PROCEDURE_NAME = Publication.CatalogChangeQueueReader, MAX_QUEUE_READERS = 10, EXECUTE AS ‘SSBTestUserName’ ) GO USE AdventureWorks2008 GO CREATE PROC Production.CatalogChangeAckQueueReader AS GO CREATE QUEUE Production.CatalogChangeAckQueue WITH STATUS = ON, ACTIVATION ( STATUS = ON, PROCEDURE_NAME = Production.CatalogChangeAckQueueReader, ptg 1973 Understanding Service Broker Constructs 49 MAX_QUEUE_READERS = 10, EXECUTE AS ‘SSBTestUserName’ ) The code in Listing 49.3 declares an empty stored procedure for each queue. You can fill this shell after you define the services. Defining Services to Send and Receive Messages Services represent the endpoints in Service Broker applications. You can think of them as the glue that binds contracts with queues. This binding ensures that the typed messages specified in the contract end up in the appropriate queues. Here is the DDL syntax for creating services: CREATE SERVICE ServiceName [AUTHORIZATION OwnerName] ON QUEUE [SchemaName.]QueueName [( ContractName | [ DEFAULT ] [ , n ] )] [;] For this example, you need to create two services: the initiator in AdventureWorks2008 and the target in XCatMgmt. This is the initiator in AdventureWorks2008: USE AdventureWorks2008 GO CREATE SERVICE [//samspublishing.com/SS2008/SSB/Services/CatalogChangeInitiatorService] AUTHORIZATION [SSBTestUserName] ON QUEUE Production.CatalogChangeAckQueue ([//samspublishing.com/SS2008/SSB/Contracts/BasicCatalogChangeContract]) And this is the target in XCatMgmt: USE XCatMgmt GO CREATE SERVICE [//samspublishing.com/SS2008/SSB/Services/CatalogMaintenanceService] AUTHORIZATION [SSBTestUserName] ON QUEUE Publication.CatalogChangeQueue ([//samspublishing.com/SS2008/SSB/Contracts/BasicCatalogChangeContract]) As you can see, creating services is simple. Now that all the plumbing is in place, you can begin the dialog between the services. . loosely coupled. ptg 1966 CHAPTER 49 SQL Server Service Broker The dialog messages are typed to constrain and (optionally) validate their content. You use the new SQL Server database object MESSAGE. you need to create a Windows user on the local server and associate a SQL Server login with it, giving it db_owner permissions in both AdventureWorks2008 and XCatMgmt. You need to specify this. initiator in AdventureWorks2008 and the target in XCatMgmt. This is the initiator in AdventureWorks2008: USE AdventureWorks2008 GO CREATE SERVICE [//samspublishing.com/SS2008/SSB/Services/CatalogChangeInitiatorService] AUTHORIZATION

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

TỪ KHÓA LIÊN QUAN