Programming Microsoft SQL Server 2005



Similar documents
SQL Server Administrator Introduction - 3 Days Objectives

SSIS Training: Introduction to SQL Server Integration Services Duration: 3 days

Microsoft SQL Server 2008 Step by Step

An Overview of SQL CLR

Delivering Business Intelligence With Microsoft SQL Server 2005 or 2008 HDT922 Five Days

LearnFromGuru Polish your knowledge

About the Authors About the Technical Reviewers Acknowledgments

SQL SERVER TRAINING CURRICULUM

Beginning C# 5.0. Databases. Vidya Vrat Agarwal. Second Edition

SQL Server 2005 Features Comparison

SQL Server for developers. murach's TRAINING & REFERENCE. Bryan Syverson. Mike Murach & Associates, Inc. Joel Murach

SQL Server 2008 Administration

Excel Excel 97 Add-In. Excel 2010 PowerPivot. Excel Add-In Pivot Table Services Office Web Components

Pro SQL Server Reporting Services. Third Edition. mm m. Brian McDonald. Shawn McGehee. Rodney Landrum. Apress*

Beginning SQL Server Administration. Apress. Rob Walters Grant Fritchey

COURSE SYLLABUS COURSE TITLE:

Microsoft SQL Server 2008 Administrator's Pocket Consultant

SQL Server Integration Services. Design Patterns. Andy Leonard. Matt Masson Tim Mitchell. Jessica M. Moss. Michelle Ufford

SQL Server 2005 Reporting Services (SSRS)

How To Use A Microsoft Sql Server 2005

CHAPTER 4: BUSINESS ANALYTICS

Release 2.1 of SAS Add-In for Microsoft Office Bringing Microsoft PowerPoint into the Mix ABSTRACT INTRODUCTION Data Access

AV-005: Administering and Implementing a Data Warehouse with SQL Server 2014

Visual Basic. murach's TRAINING & REFERENCE

Reviewing Microsoft SQL Server 2005 Management Tools

Microsoft SQL Server 2008 Bible

Outlines. Business Intelligence. What Is Business Intelligence? Data mining life cycle

Social Relationship Analysis with Data Mining

SQL Server Training Course Content

Getting to Know the Tools

Business Benefits From Microsoft SQL Server Business Intelligence Solutions How Can Business Intelligence Help You? PTR Associates Limited

Author: Ryan J Adams. Overview. Policy Based Management. Terminology

Microsoft Corporation. Project Server 2010 Installation Guide

BUILDER 3.0 Installation Guide with Microsoft SQL Server 2005 Express Edition January 2008

Implementing Data Models and Reports with Microsoft SQL Server 20466C; 5 Days

Dynamic Web Programming BUILDING WEB APPLICATIONS USING ASP.NET, AJAX AND JAVASCRIPT

SQL Server Analysis Services Complete Practical & Real-time Training

Windchill Service Information Manager Curriculum Guide

form approved June/2006 revised Nov Page 1 of 7

SQL SERVER DEVELOPER Available Features and Tools New Capabilities SQL Services Product Licensing Product Editions Will teach in class room

Creating a Patch Management Dashboard with IT Analytics Hands-On Lab

Connectivity Pack for Microsoft Guide

SQL SERVER BUSINESS INTELLIGENCE (BI) - INTRODUCTION

SOFTWARE TESTING TRAINING COURSES CONTENTS

New 11g Features in Oracle Developer Tools for Visual Studio. An Oracle White Paper January 2008

Getting Started with the Ed-Fi ODS and Ed-Fi ODS API

Windchill PDMLink Curriculum Guide

SQL Server 2012 Business Intelligence Boot Camp

Microsoft SQL Server 2005 Reporting Services Step by Step

How to test and debug an ASP.NET application

Microsoft SQL Server Security Best Practices

Expanded contents. Section 1. Chapter 2. The essence off ASP.NET web programming. An introduction to ASP.NET web programming

NNT CIS Microsoft SQL Server 2008R2 Database Engine Level 1 Benchmark Report 0514a

Jet Data Manager 2012 User Guide

FHE DEFINITIVE GUIDE. ^phihri^^lv JEFFREY GARBUS. Joe Celko. Alvin Chang. PLAMEN ratchev JONES & BARTLETT LEARN IN G. y ti rvrrtuttnrr i t i r

Creating Dashboards for Microsoft Project Server 2010

Microsoft' Excel & Access Integration

Microsoft Implementing Data Models and Reports with Microsoft SQL Server

for Networks Installation Guide for the application on the server August 2014 (GUIDE 2) Lucid Exact Version 1.7-N and later

A Tutorial on SQL Server CMPT 354 Fall 2007

for Networks Installation Guide for the application on the server July 2014 (GUIDE 2) Lucid Rapid Version 6.05-N and later

Microsoft End to End Business Intelligence Boot Camp

How To Create An Easybelle History Database On A Microsoft Powerbook (Windows)

Licenze Microsoft SQL Server 2005

Developing and Deploying SQL Server Applications on HP Integrity Servers

Introduction. It has been just over six years since SQL Server 2000 was

Comparing SQL Server 2005 and IBM DB2 v8.2 as a Database Platform for Visual Studio and.net Developers

SQL Server Integration Services Design Patterns

J j enterpririse. Oracle Application Express 3. Develop Native Oracle database-centric web applications quickly and easily with Oracle APEX

BI xpress Product Overview

Top 10 Oracle SQL Developer Tips and Tricks

Introduction. Part I: Finding Bottlenecks when Something s Wrong. Chapter 1: Performance Tuning 3

SAS BI Dashboard 4.3. User's Guide. SAS Documentation

Microsoft Dynamics GP. econnect Installation and Administration Guide Release 9.0

DiskBoss. File & Disk Manager. Version 2.0. Dec Flexense Ltd. info@flexense.com. File Integrity Monitor

RDS Migration Tool Customer FAQ Updated 7/23/2015

The safer, easier way to help you pass any IT exams. Exam : TS:MS SQL Server 2008.Business Intelligence Dev and Maintenan.


ASP.NET Using C# (VS2012)

Google AdWords, 248 Google Analytics tools, 248 GoogleAdsExtract.xlsx file, 161 GoogleAnalytics, 161

Office 2010 Workflow;

$99.95 per user. SQL Server 2008/R2 Reporting Services CourseId: 162 Skill level: Run Time: 37+ hours (195 videos)

2074 : Designing and Implementing OLAP Solutions Using Microsoft SQL Server 2000

Installing Globodox Web Client on Windows Server 2012

SQL Server Management Studio

OneStop Reporting 3.7 Installation Guide. Updated:

NUTECH COMPUTER TRAINING INSTITUTE 1682 E. GUDE DRIVE #102, ROCKVILLE, MD WEB: TEL:

SAP BusinessObjects Business Intelligence (BI) platform Document Version: 4.1, Support Package Report Conversion Tool Guide

Visual COBOL ASP.NET Shopping Cart Demonstration

Workflow Administration of Windchill 10.2

MODULE FRAMEWORK : Dip: Information Technology Network Integration Specialist (ITNIS) (Articulate to Edexcel: Adv. Dip Network Information Specialist)

SourceAnywhere Service Configurator can be launched from Start -> All Programs -> Dynamsoft SourceAnywhere Server.

Course: SharePoint 2013 Business Intelligence

MS 50511A The Microsoft Business Intelligence 2010 Stack

Microsoft SQL Server 2005 Product Overview

End to End Microsoft BI with SQL 2008 R2 and SharePoint 2010

Special Edition for FastTrack Software

MicrosoftDynam ics GP TenantServices Installation and Adm inistration Guide

Chapter 4 Accessing Data

ecopy ShareScan 5.0 SQL installs guide

Transcription:

Programming Microsoft SQL Server 2005 Andrew J. Brust, Stephen Forte To learn more about this book, visit Microsoft Learning at http://www.microsoft.com/mspress/books/9153.aspx 9780735619234 Publication Date: December 2004

Table of Contents Acknowledgements....................................................... xix Introduction............................................................. xxiii Who This Book Is For..................................................... xxiv How This Books is Organized.............................................. xxv System Requirements..................................................... xxvi Using the Samples...................................................... xxvii Support for This Book.................................................... xxix Questions and Comments........................................... xxix Part I Design Fundamentals and Core Technologies 1 Overview......................................................3 A Tough Act to Follow...................................................... 3 The Software Industry and Disruptive Change........................... 3 Industry Trends, SQL Server Features, and a Book to Show You the Way........... 4 Programming the Server.............................................. 4 Application Code and SQL Server: Extending Your Database s Reach........ 5 It s the Strategy, Stupid............................................... 7 A Collaborative Effort for, and by, Developers.................................. 9 2 Exploring the T-SQL Enhancements in SQL Server 2005............ 11 Introducing SQL Server Management Studio................................. 12 Common Table Expressions................................................. 13 Recursive Queries with CTEs.......................................... 16 The PIVOT and UNPIVOT Operators......................................... 20 Using UNPIVOT.................................................... 21 Dynamically Pivoting Columns........................................ 22 The APPLY Operator................................................. 24 TOP Enhancements....................................................... 25 Ranking Functions........................................................26 ROW_NUMBER().................................................... 26 RANK()............................................................ 30 DENSE_RANK() and NTILE(n)......................................... 32 Using All the Ranking Functions Together.............................. 34 Ranking over Groups: PARTITION BY.................................. 35 What do you think of this book? We want to hear from you! Microsoft is interested in hearing your feedback about this publication so we can continually improve our books and learning resources for you. To participate in a brief online survey, please visit: www.microsoft.com/learning/booksurvey/ vii

viii Table of Contents Exception Handling in Transactions......................................... 38 New Data Types.......................................................... 40 varchar(max) Data Type............................................. 40 xml Data Type...................................................... 40 The WAITFOR Command.................................................. 41 DDL Triggers and Notifications............................................. 42 SNAPSHOT Isolation...................................................... 43 Statement-Level Recompile................................................ 44 Summary................................................................ 44 3 An Overview of SQL CLR....................................... 45 Getting Started: Enabling CLR Integration.................................... 46 Visual Studio/SQL Server Integration........................................ 48 SQL Server Projects in Visual Studio................................... 49 Automated Deployment............................................. 51 SQL CLR Code Attributes............................................ 52 Your First SQL CLR Stored Procedure........................................ 53 CLR Stored Procedures and Server-Side Data Access........................... 55 Piping Data with SqlDataRecord and SqlMetaData...................... 57 Deployment............................................................. 59 Deploying Your Assembly............................................ 59 Deploying Your Stored Procedures.................................... 61 Testing Your Stored Procedures....................................... 63 CLR Functions............................................................ 65 CLR Triggers............................................................. 69 CLR Aggregates.......................................................... 74 CLR Types............................................................... 78 Security................................................................. 84 Examining and Managing CLR Types in a Database........................... 85 Best Practices for SQL CLR Usage........................................... 91 Summary................................................................ 92 4 XML and the Relational Database............................... 93 XML in SQL Server 2000................................................... 95 The XML Data Type....................................................... 96 Working with the XML Data Type as a Variable......................... 96 Working with XML in Tables......................................... 98 XML Schemas...................................................... 99 XML Indexes...................................................... 102 FOR XML Commands.................................................... 105 FOR XML RAW.................................................... 106 FOR XML AUTO................................................... 106 FOR XML EXPLICIT................................................. 108

Table of Contents ix OPENXML Enhancements in SQL Server 2005......................... 120 XML Bulk Load.................................................... 121 Querying XML Data Using XQuery......................................... 122 XQuery Defined................................................... 122 SQL Server 2005 XQuery in Action................................... 125 XML DML......................................................... 134 Converting a Column to XML........................................ 135 Summary............................................................... 137 5 Introducing SQL Server Management Studio.................... 139 The New Management Studio Interface..................................... 140 Overview of New Features.......................................... 140 Window Types..................................................... 141 Positioning a Docking Window...................................... 142 Window Customization Options..................................... 143 Connecting to a Database Server.................................... 144 Using Object Explorer.................................................... 145 Object Explorer Filters.............................................. 146 Management Studio Solutions, Projects, and Files............................ 149 Code and Text Editor............................................... 150 Track Changes Indicator............................................ 152 Bookmarks........................................................ 153 Creating Objects.........................................................154 Creating Tables.................................................... 154 Creating Table-Related Objects...................................... 156 Creating Indexes................................................... 156 Setting Properties for New Users..................................... 157 Generating Scripts from Objects..................................... 158 Creating Queries.........................................................158 Executing Queries.................................................. 160 Using Templates.........................................................161 Maintenance Features.................................................... 163 Using a Maintenance Plan.......................................... 164 Performance Tools....................................................... 166 SQL Server Profiler................................................. 166 Database Engine Tuning Advisor..................................... 167 Summary............................................................... 167 6 Using SQL Server Management Objects (SMO).................. 169 What Is SMO?........................................................... 170 What About SQL-DMO?............................................ 170 New Features in SMO.............................................. 174 Working with SMO in Visual Studio......................................... 174

x Table of Contents Iterating Through Available Servers.................................. 177 Retrieving Server Settings.......................................... 178 Creating Backup-and-Restore Applications............................ 182 Performing Programmatic DBCC Commands with SMO................ 188 Summary............................................................... 190 7 SQL Server 2005 Security..................................... 191 Four Themes of the Security Framework.................................... 192 Secure by Design.................................................. 192 Secure by Default.................................................. 192 Secure by Deployment............................................. 192 Communications.................................................. 192 SQL Server 2005 Security Overview........................................ 193 SQL Server Logins................................................. 194 Database Users.................................................... 194 The Guest User Account............................................ 195 Authentication and Authorization......................................... 196 How Clients Establish a Connection.................................. 196 Password Policies.................................................. 197 User-Schema Separation............................................ 199 Execution Context................................................. 201 Encryption Support in SQL Server 2005..................................... 204 Encrypting Data on the Move....................................... 205 Encrypting Data at Rest............................................ 206 Protecting SQL Server 2005............................................... 211 Reducing the Surface Area for Attack................................ 211 How Hackers Attack SQL Server........................................... 213 Direct Connection to the Internet.................................... 213 Weak SA Passwords................................................ 213 SQL Server Browser Service......................................... 213 SQL Injection..................................................... 214 Intelligent Observation............................................. 214 Summary............................................................... 215 Part II Applications Development and Reach Technologies 8 ADO.NET 2.0, Typed DataSet Objects, and.net Data Binding...... 219 A Brief History of Data Access Object Models............................... 220 DAO: A Golden Oldie.............................................. 220 RDO: A Thin API Wrapper.......................................... 220 Enter OLE DB and ADO Classic..................................... 220 ADO +.NET = ADO.NET............................................ 221 What s New in ADO.NET 2.0?.............................................. 221

Table of Contents xi New Typed DataSet Members....................................... 222 Other Enhancements............................................... 222 Typed DataSet Enhancements............................................. 223 DataTable Objects in the Typed DataSet Designer...................... 225 TableAdapter Objects............................................... 226 Connection String Management..................................... 226 Using the TableAdapter Configuration Wizard......................... 228 More on Queries and Parameters.................................... 230 Adding Query Objects.............................................. 231 DBDirect Methods and Connected Use of Typed DataSet Objects........ 232 Standalone DataTable Objects....................................... 233 Pure ADO.NET: Working in Code......................................... 233 Querying 101..................................................... 234 Keeping Data Up to Date........................................... 235 Responsive UIs: Executing Queries Asynchronously..................... 237 Not for Servers Only: Client-Side Bulk Copy........................... 242 It s Not Just Text: Processing XML Columns with ADO.NET and the System.Xml Namespace............................................... 244 Nothing but.net: Consuming SQL CLR UDT Data as Native.NET Objects................................................ 245 Back to the Drawing Board.......................................... 246 Embedding SQL CLR Objects in Typed DataSet Objects....................... 247 Adding a CLR Stored Procedure to a Typed DataSet.................... 247 TVFs: Easy Living................................................... 249 Aggregates and UDTs.............................................. 250 Windows Forms Data Binding............................................. 251 DataGridView Binding.............................................. 252 Details View Binding............................................... 253 Smart Defaults.................................................... 253 Binding to Stored Procedures and Views.............................. 254 SQL CLR Binding................................................... 254 Master-Detail and Lookup Binding................................... 254 Parameterized Query Data Binding................................... 257 Data Binding on the Web................................................. 258 Typed DataSet Objects and the Web.config File........................ 258 The Data Source Configuration Wizard, the ObjectDataSource Control, and the New Data-Bound Controls........................... 259 Summary............................................................... 260 9 Debugging................................................. 261 About the Sample Code.................................................. 262 Ad Hoc Debugging...................................................... 264 Creating Database Connections...................................... 264

xii Table of Contents T-SQL Step Into Debugging....................................... 267 Application Debugging................................................... 276 Entering Debugging Mode......................................... 279 Debugging SQL CLR Code.......................................... 280 Breakpoints and Context Switching.................................. 283 Mixing SQL CLR and T-SQL Code.......................................... 284 Test Script Debugging.................................................... 289 Debugging Queries External to Visual Studio................................ 289 Remote Debugging...................................................... 292 Server Configuration............................................... 292 Server Firewall Considerations....................................... 294 Back to the Client................................................. 295 Client Firewall Configuration........................................ 295 Attaching to a Remote Process...................................... 297 Summary............................................................... 299 10 SQL Server 2005 Native XML Web Services...................... 301 Understanding Native XML Web Services................................... 302 Comparing Native XML Web Services and SQLXML.................... 302 Exposing SQL Programmability as Web Services............................. 303 Stored Procedures and User-Defined Functions........................ 303 SQL Batch........................................................ 303 Reserving URLs with Http.sys........................................ 303 Creating and Managing Endpoints................................... 304 Granting Endpoint Permissions...................................... 309 Calling Native XML Web Service Endpoints from Client Applications..... 310 Example Native XML Web Services Project.................................. 312 Creating the SQL Server Functionality................................ 312 Registering the URL with Http.sys.................................... 316 Exposing the Endpoints............................................ 316 Granting Security Access to the Endpoints............................ 317 Creating the Client Application...................................... 319 Best Practices for Using Native XML Web Services........................... 324 Advantages of Native XML Web Services............................. 325 Limitations of Native XML Web Services.............................. 325 Security Recommendations......................................... 326 Performance Recommendations..................................... 326 When to Avoid Native XML Web Services............................. 326 When to Use Native XML Web Services............................... 327 Summary............................................................... 328

Table of Contents xiii 11 Transactions................................................ 329 What Is a Transaction?.................................................... 330 Understanding the ACID Properties.................................. 330 Local Transactions Support in SQL Server 2005............................... 332 Autocommit Transaction Mode...................................... 333 Explicit Transaction Mode........................................... 333 Implicit Transaction Mode.......................................... 336 Batch-Scoped Transaction Mode..................................... 337 Using Local Transactions in ADO.NET................................. 338 Transaction Terminology.................................................. 340 Isolation Levels.......................................................... 341 Isolation Levels in SQL Server 2005................................... 341 Isolation Levels in ADO.NET......................................... 346 Distributed Transactions.................................................. 347 Distributed Transaction Terminology................................. 348 Rules and Methods of Enlistment.................................... 349 Distributed Transactions in SQL Server 2005........................... 351 Distributed Transactions in the.net Framework....................... 352 Using a Resource Manager in a Successful Transaction.................. 360 Transactions in SQL CLR (CLR Integration)................................... 364 Putting It All Together.................................................... 368 Summary............................................................... 369 12 SQL Server Service Broker: The New Middleware................. 371 What Is Middleware?..................................................... 371 What Is SQL Server Service Broker?......................................... 372 Comparing Service Broker and MSMQ................................ 372 What Is a SQL Server Service Broker Application?............................ 373 Service Broker Architecture................................................ 374 Integrated Management and Operation.................................... 377 Routing and Load Balancing............................................... 377 Service Broker Programming in T-SQL...................................... 379 A Word About Programming Languages.............................. 380 Enabling Service Broker............................................. 380 Defining Service Broker Objects............................................ 380 The Sending Service Program....................................... 382 The Receiving Service Program...................................... 383 Running the Application............................................ 385 A More Robust, Real-World Application............................... 386 Service Broker and Query Notification...................................... 387 Service Broker s Place in the Middleware World.............................. 391 Summary............................................................... 392

xiv Table of Contents 13 Using SQL Server 2005 Notification Services.................... 393 What Is a Notification Application?........................................ 393 Notification Services Components................................... 394 Notification Services Deployment Strategies.......................... 396 Working with Notification Services......................................... 397 Creating Notification Applications................................... 398 A Sample Notification Application......................................... 400 Flight Price Notification Sample Application.......................... 400 Summary............................................................... 424 14 Developing Desktop Applications with SQL Server Express Edition............................... 427 What Is SQL Server Express Edition?........................................ 427 Licensing......................................................... 429 Feature Review.................................................... 429 SQL Server 2005 Express Edition with Advanced Services............... 431 Configuration........................................................... 435 Working with SQL Server Express Edition................................... 437 SQLCMD Command-Line Tool....................................... 442 User Instances..................................................... 446 SSEUTIL.......................................................... 449 Installing SQL Server Express Edition....................................... 451 Using the Setup Wizard to Manually Install Express Edition.............. 452 Installing via Command-Line Parameters or a Configuration File......... 456 Deploying Express Edition Applications Using a Wrapper............... 460 Deploying Express Edition Applications Using ClickOnce................ 471 Updating ClickOnce Deployments That Use Express Edition............. 475 Summary............................................................... 485 15 Developing Applications with SQL Server 2005 Everywhere Edition and SQL Server Merge Replication............................. 487 SQL Everywhere Integration with SQL Server 2005.......................... 488 Working with SQL Everywhere Databases in Management Studio........ 489 Working with SQL Everywhere Data in Management Studio............. 493 Creating a SQL Everywhere Application with SQL Server Replication and Visual Studio 2005................................................... 496 Creating a Publication.............................................. 498 Installing and Configuring SQL Everywhere Server Components for IIS................................................ 505 Creating a Subscription Using Management Studio.................... 508 Creating a Mobile Application Using Visual Studio 2005................ 513 Summary............................................................... 520

Table of Contents xv Part III Reporting and Business Intelligence 16 Using SQL Server 2005 Integration Services..................... 523 History of Data Transfer in SQL Server...................................... 523 DTS Packages..................................................... 524 Working with Integration Services Packages................................. 524 Control Flow...................................................... 524 Data Flow......................................................... 526 Using Integration Services Packages........................................ 532 Creating Packages Using the Import And Export Wizard................ 532 Creating Packages Using BI Development Studio....................... 533 Managing Packages Using Management Studio....................... 533 Using the Command Line to Execute and Manage Packages............ 533 Scheduling Packages Using SQL Server Agent......................... 534 Configuring and Deploying Packages................................. 535 Overview of Programming Package Extension......................... 536 Security................................................................ 537 Dealing with Sensitive Information and Assets........................ 537 Considerations for Working on a Single Development Machine.......... 538 Considerations for Workgroups...................................... 538 Programming Integration Services......................................... 539 Programming in Visual Studio....................................... 539 Loading and Executing Packages in Applications....................... 539 Creating Packages Programmatically................................. 540 Extensibility............................................................. 554 Script Tasks....................................................... 554 Custom Tasks...................................................... 555 Custom Components.............................................. 556 Script Components................................................. 566 Custom Connection Managers....................................... 571 Log Providers..................................................... 572 Foreach Enumerator............................................... 572 Summary............................................................... 572 17 Basic OLAP................................................. 573 Wherefore BI?........................................................... 573 OLAP 101............................................................... 575 OLAP Vocabulary.................................................. 576 Dimensions, Axes, Stars, and Snowflakes.............................. 576 Building Your First Cube.................................................. 578 Preparing Star Schema Objects...................................... 579 A Tool by Any Other Name.......................................... 579

xvi Table of Contents Creating the Project............................................... 581 Adding a Data Source View......................................... 582 Creating a Cube with the Cube Wizard............................... 586 Using the Cube Designer........................................... 589 Using the Dimension Wizard........................................ 591 Using the Dimension Designer...................................... 594 Working with the Properties Window and Solution Explorer............. 596 Processing the Cube............................................... 597 Running Queries........................................................ 597 Summary............................................................... 599 18 Advanced OLAP............................................. 601 What We ll Cover in This Chapter.......................................... 602 MDX in Context................................................... 602 And Now a Word from Our Sponsor................................ 603 Advanced Dimensions and Measures....................................... 603 Keys and Names................................................... 604 Changing the All Member.......................................... 606 Adding a Named Query to a Data Source View........................ 607 Parent-Child Dimensions........................................... 609 Member Grouping................................................. 614 Server Time Dimensions............................................ 615 Fact Dimensions................................................... 617 Role-Playing Dimensions........................................... 620 Advanced Measures............................................... 621 Calculations............................................................. 622 Calculated Members............................................... 623 Named Sets....................................................... 629 More on Script View............................................... 629 Key Performance Indicators............................................... 633 KPI Visualization: Status and Trend................................... 634 A Concrete KPI.................................................... 635 Testing KPIs in Browser View........................................ 637 KPI Queries in Management Studio.................................. 639 Other BI Tricks in Management Studio............................... 643 Actions................................................................. 645 Actions Simply Defined............................................. 645 Designing Actions................................................. 645 Testing Actions.................................................... 647 Partitions, Aggregation Design, Storage Settings, and Proactive Caching........ 648 Editing and Creating Partitions...................................... 649 Aggregation Design............................................... 651 Partition Storage Options........................................... 652

Table of Contents xvii Proactive Caching.................................................. 652 Additional Features and Tips........................................ 654 Perspectives............................................................. 654 Translations............................................................. 657 Roles................................................................... 662 Summary............................................................... 665 19 OLAP Application Development............................... 667 Using Excel.............................................................. 668 Working Within Excel.............................................. 669 Using PivotTables and Charts in Applications and Web Pages............ 676 Beyond OWC: Full-On OLAP Development.................................. 691 MDX and Analysis Services APIs...................................... 691 Moving to MDX................................................... 692 Management Studio as an MDX Client................................ 692 OLAP Development with ADO MD.NET............................... 706 XMLA at Your (Analysis) Service...................................... 718 Analysis Services CLR Support: Server-Side ADO MD.NET................ 729 Summary............................................................... 739 20 Extending Your Database System with Data Mining.............. 741 Why Mine Your Data?.................................................... 742 Getting Started.......................................................... 745 Preparing Your Source Data......................................... 745 Creating Training and Test Samples................................... 747 Adding an SSAS Project............................................. 752 Using the Data Mining Wizard and Data Mining Designer..................... 752 Creating a Mining Structure......................................... 755 Creating a Mining Model........................................... 755 Editing and Adding Mining Models.................................. 758 Deploying and Processing Data Mining Objects........................ 763 Viewing Mining Models............................................ 765 Validating and Comparing Mining Models............................ 773 Nested Tables..................................................... 776 Using Data Mining Extensions............................................. 782 Data Mining Modeling Using DMX................................... 782 Data Mining Predictions Using DMX................................. 792 DMX Templates.................................................... 799 Data Mining Applied..................................................... 800 Data Mining and API Programming.................................. 801 Using the WinForms Model Content Browser Controls.................. 801 Executing Prediction Queries with ADO MD.NET....................... 804

xviii Table of Contents Model Content Queries............................................ 804 ADO MD.NET and ASP.NET......................................... 805 Using the Data Mining Web Controls................................ 805 Developing Managed Stored Procedures............................. 806 XMLA and Data Mining............................................ 808 Data Mining and Reporting Services................................. 810 Summary............................................................... 817 21 Reporting Services........................................... 819 Report Definition and Design............................................. 820 Data Sources...................................................... 820 Report Layouts.................................................... 822 Report Designer................................................... 826 Report Builder.................................................... 838 Report Definition Language......................................... 843 Report Management..................................................... 843 Publishing........................................................ 843 Report Manager................................................... 844 SQL Server Management Studio..................................... 851 Command-Line Utilities............................................ 852 Programming: Management Web Services............................ 852 Report Access and Delivery............................................... 852 Delivery on Demand............................................... 852 Subscriptions..................................................... 855 Presentation Formats.............................................. 857 Programming: Rendering........................................... 859 Report Server Architecture................................................ 862 Deployment Modes................................................ 865 Extensibility....................................................... 865 Report Integration................................................. 867 Summary............................................................... 867 Index.................................................................... 869 What do you think of this book? We want to hear from you! Microsoft is interested in hearing your feedback about this publication so we can continually improve our books and learning resources for you. To participate in a brief online survey, please visit: www.microsoft.com/learning/booksurvey/

Chapter 3 An Overview of SQL CLR Andrew Brust In this chapter: Getting Started: Enabling CLR Integration................................ 46 Visual Studio/SQL Server Integration..................................... 48 Your First SQL CLR Stored Procedure..................................... 53 CLR Stored Procedures and Server-Side Data Access........................ 55 Deployment.......................................................... 59 CLR Functions......................................................... 65 CLR Triggers.......................................................... 69 CLR Aggregates....................................................... 74 CLR Types............................................................ 78 Security.............................................................. 84 Examining and Managing CLR Types in a Database......................... 85 Best Practices for SQL CLR Usage........................................ 91 Summary............................................................. 92 The banner headline for Microsoft SQL Server 2005 is its integration of the Microsoft.NET common language runtime (CLR). This architectural enhancement means that SQL Server can use certain.net classes as basic data types and can accommodate the use of.net languages for the creation of stored procedures, triggers, and functions, and even user-defined aggregates. Note Throughout this chapter, we will refer to the CLR integration in SQL Server as SQL CLR features, functionality, or integration, and we will refer to stored procedures, triggers, functions, aggregates, and user-defined types as the five basic SQL CLR entities. Let s face facts: Transact SQL (T-SQL) is essentially a hack. Back when SQL Server was first developed, Microsoft and Sybase took SQL a declarative, set-based language and added variable declaration, conditional branching, looping, and parameterized subroutine logic to make it into a quasi-procedural language. Although extremely clever and useful, T-SQL lacked, and still lacks, many of the niceties of a full-fledged procedural programming language. 45

46 Part I: Design Fundamentals and Core Technologies This shortcoming has forced some people to write T-SQL stored procedures that are overly complex and difficult to read. It has forced others to put logic in their middle-tier code that they would prefer to implement on the database. And it s even forced some people to abandon stored procedures altogether and use dynamic SQL in their applications, a practice that we do not endorse. Because of these workarounds to address T-SQL s procedural limitations, CLR integration is a welcome new feature in SQL Server, and it has caught the market s attention. Meanwhile, T-SQL and, one might argue, SQL itself is vastly superior to procedural languages for querying and manipulating data. Its set-based syntax and implementation simply transcend the approach of procedurally iterating through rows of data. This is no less true in SQL Server 2005 than in previous versions of the product, and T-SQL has been greatly enhanced in this release (as detailed in Chapter 2), making it more valuable still. So this places database application developers at a crossroads. We must simultaneously learn how the SQL CLR features work and develop a sophisticated, judicious sense of when to use T-SQL instead of the SQL CLR feature set. We must resist the temptation to completely.netify our databases but learn to take advantage of the SQL CLR feature set where and when prudent. This chapter aims to help you learn to use SQL CLR features and to develop an instinct for their appropriate application. In this chapter, you will learn: How to enable (or disable) SQL CLR integration on your SQL Server How SQL Server accommodates CLR code, through the loading of.net assemblies How to use SQL Server 2005 and Visual Studio 2005 together to write SQL CLR code and deploy it, simply and quickly How to deploy SQL CLR code independently of Visual Studio, using T-SQL commands, with or without the help of SQL Server Management Studio How to create simple CLR stored procedures, triggers, functions, aggregates, and userdefined types, use them in your databases, and utilize them from T-SQL How both the standard SQL Server client provider and the new server-side library can be combined to implement SQL CLR functionality How SQL CLR security works and how to configure security permissions for your assemblies When to use SQL CLR functionality, and when to opt to use T-SQL instead Getting Started: Enabling CLR Integration Before you can learn how to use SQL CLR features, you need to know how to enable them. As with many new products in the Microsoft Windows Server System family, many advanced features of SQL Server 2005 are disabled by default. The reasoning behind this is sound: Each

Chapter 3: An Overview of SQL CLR 47 additional feature that is enabled provides extra surface area for attacks on security or integrity of the product, and the added exposure is inexcusable if the feature goes unused. The SQL CLR features of SQL Server 2005 are sophisticated and can be very useful, but they are also, technically, nonessential. It is possible to build high-performance databases and server-side programming logic without SQL CLR integration, so it is turned off by default. Don t be discouraged, though: Turning on the feature is easy. Microsoft provides both a user-friendly GUI tool (aptly named the SQL Server Surface Area Configuration tool) and a system stored procedure for enabling or disabling SQL CLR integration. We ll cover both approaches. To use the Surface Area Configuration tool, simply start it from the Configuration Tools subgroup in the Microsoft SQL Server 2005 programs group on the Windows start menu. Figure 3-1 shows the tool as it appears upon startup. Figure 3-1 The SQL Server 2005 Surface Area Configuration tool To configure CLR integration, click the Surface Area Configuration For Features link at the bottom of the form. After a short pause, the Surface Area Configuration For Features dialog box appears; a tree view-style list of features appears on the left, and the Ad Hoc Remote Queries feature is preselected. Click the CLR Integration node immediately below it, and you will see an Enable CLR Integration check box on the right of the form. (This is shown in Figure 3-2.) To enable SQL CLR features, make sure that the check box is checked, and click OK to close the Surface Area Configuration For Features window. (You can also clear the check box to disable SQL CLR integration.) Close the Surface Area Configuration tool by clicking its close box in the upper-right corner of the window.

48 Part I: Design Fundamentals and Core Technologies Figure 3-2 The Surface Area Configuration For Features window If you d prefer a command-line method for enabling or disabling SQL CLR functionality, open up SQL Server Management Studio and connect to the server you d like to configure. Then, from a query window, type the following commands, and click the Execute button on the Management Studio SQL Editor toolbar. sp_configure 'clr enabled', 1 GO RECONFIGURE GO That s all there is to it! To disable SQL CLR integration, just use a value of 0, instead of 1, as the second parameter value in the sp_configure call. Tip Don t forget that this will work from any tool that can connect to SQL Server, not just Management Studio. In fact, you could issue the previous command text from your own code using the ADO.NET SqlCommand object s ExecuteNonQuery method as long as your code can connect to your server and your sever can authenticate as a user in the sysadmin server role. With SQL CLR integration enabled, you re ready to get started writing SQL CLR code. Before we dive in, we need to discuss Visual Studio/SQL Server integration and when to use it. Visual Studio/SQL Server Integration Visual Studio 2005 and SQL Server 2005 integrate tightly in a number of ways. It s important to realize, however, that the use of Visual Studio integration is completely optional and the use of T-SQL is a sufficient substitute. T-SQL has been enhanced with new DDL commands for

Chapter 3: An Overview of SQL CLR 49 maintaining CLR assemblies, types, and aggregates, and its existing commands for stored procedures, triggers, and functions have been enhanced to recognize code within deployed assemblies. Visual Studio can execute those commands on your behalf. It can also make writing individual SQL CLR classes and functions easier. Ultimately, we think all developers should be aware of both Visual Studio assisted and more manual coding and deployment methods. You might decide to use one method most of the time, but in some situations you ll probably need the other, so we want to prepare you. As we cover each major area of SQL CLR programming, we will discuss deployment from both points of view. We ll cover some general points about Visual Studio integration now, and then we ll move on to cover SQL CLR development. SQL Server Projects in Visual Studio The combination of Visual Studio 2005 and SQL Server 2005 on the same development machine provides a special SQL Server Project type in Visual Studio and, within projects of that type, defined templates for the five basic SQL CLR entities. These templates inject specific code attributes and function stubs that allow you to create SQL CLR code easily. The attributes are used by Visual Studio to deploy your assembly and its stored procedures, triggers, and so on to your database. Some of them are also used by SQL Server to acknowledge and properly use your functions, user-defined types (UDTs), and aggregates. To test out the new project type and templates, start Visual Studio 2005 and create a new project by using the File/New/Project main menu option, the New Project toolbar button, the Ctrl+Shift+N keyboard accelerator, or the Create Project hyperlink on the Visual Studio Start Page. In the New Project dialog box (Figure 3-3), select Database from the Project types tree view on the left (the Database node appears under the parent node for your programming language of choice; in Figure 3-3, the language is C#), and click the SQL Server Project icon in the Templates list on the right. Enter your own project name if you d like, and click OK. Figure 3-3 The Visual Studio 2005 New Project dialog box with the SQL Server project type selected

50 Part I: Design Fundamentals and Core Technologies Next, the Add Database Reference dialog box appears (Figure 3-4). Figure 3-4 The Add Database Reference dialog box Because Visual Studio provides automated deployment of your SQL CLR code, it must associate your project with a specific server and database via a database reference (connection). Any database connections that have already been defined in the Server Explorer window appear in this window, as does an Add New Reference button that allows you to define a new connection, if necessary. Pick an existing connection or define a new one, and then click OK. The project opens. Note If no data connections have already been defined in the Server Explorer window, the New Database Reference dialog box will appear in place of the Add Database Reference dialog box. In the New Database Reference dialog box, you may specify server, login, and database details for a new database connection that will be used by your project as its database reference and added to the Server Explorer as a new data connection. You can easily add preconfigured classes for the five basic SQL CLR entities to your project. You can do this in a number of ways: directly from the Project menu or from the Add submenu on the Server Explorer s project node shortcut menu (Figure 3-5). You can also add the preconfigured classes from the Add New Item dialog box (Figure 3-6), which is available from the Project/Add New Item option on the main menu, or the Add/ New Item option on the Solution Explorer project node s shortcut menu.

Chapter 3: An Overview of SQL CLR 51 Figure 3-5 The Server Explorer project node shortcut menu and its Add submenu Figure 3-6 The Visual Studio SQL Server project Add New Item dialog box Automated Deployment Once opened, SQL Server projects add a Deploy option to the Visual Studio Build menu. In addition, the Play (Start Debugging) button and the Start Debugging, Start Without Debugging, and Step Over options on the Debug menu (and their keyboard shortcuts F5, Ctrl+F5, and F10, respectively) all deploy the project assembly in addition to performing their listed function.

52 Part I: Design Fundamentals and Core Technologies Visual Studio can do a lot of deployment work for you. But as you ll learn, you can do so on your own and, in certain circumstances, have more precise control over the deployment process when you do so. SQL CLR Code Attributes A number of.net code attributes are provided for SQL CLR developers; these are contained in the Microsoft.SqlServer.Server namespace. Many of them are inserted in your code when you use the various templates in the SQL Server project type, as is a using statement for the Microsoft.SqlServer.Server namespace itself. If you choose to develop code without these templates, you must add the appropriate attributes, and optionally the using statement, yourself. Although all these attributes are provided in the same namespace, some are used exclusively by Visual Studio and others are used by both Visual Studio and SQL Server. Covering all SQL CLR attributes and their parameters would itself require an entire chapter, so our coverage will be intentionally selective. Specifically, we will provide coverage of the SqlProcedure, SqlFunction, SqlTrigger, SqlUserDefinedAggregate, and SqlUserDefinedType attributes. We will not cover the SqlFacet and SqlMethod attributes. Just as certain attributes are not covered here, we cover only some of the parameters accepted by the attributes that we do cover. And in some cases, we cover only certain of the possible values that can be passed to these attributes. For example, SqlFunction accepts several parameters but the only ones we will cover are Name, FillRowMethodName, and TableDefinition. For SqlUserDefinedAggregate and SqlUserDefinedType, we will cover only a single value setting for the Format parameter, and will not cover the several other parameters those two attributes accept. The coverage we provide will be more than sufficient for you to implement basic, intermediate, and certain advanced functionality with all the basic five SQL CLR entities. The attributes and parameters that we won t cover are useful mostly for optimizing your SQL CLR code, and they are well documented in SQL Server Books Online and articles on MSDN. About the Sample Code The sample.net code for this chapter is provided in two versions. The primary material is supplied as a Visual Studio SQL Server project, accessible by opening the solution file Chapter03.sln in the Chapter03 subfolder of this chapter s VS sample code folder. We also supply the code as a standard Class Library project, accessible by opening the solution file Chapter03Manual.sln in the Chapter03Manual subfolder. The code in each project is virtually identical, although the Class Library project does not autodeploy when the various Build and Debug options are invoked in Visual Studio 2005. As we cover each SQL CLR feature, we ll discuss how automated deployment takes place from the SQL Server project and how command-driven deployment should be performed for the Class Library project.