SQL Server 2000 Stored Procedure & XML Programming TM Second Edition Dejan Šunderic McGraw-Hill/Osborne New York Chicago San Francisco Lisbon London Madrid Mexico City Milan New Delhi San Juan Seoul Singapore Sydney Toronto McGraw-Hill/Osborne 2100 Powell Street, 10th Floor Emeryville, California 94608 U.S.A To arrange bulk purchase discounts for sales promotions, premiums, or fund-raisers, please contact McGraw-Hill/Osborne at the above address For information on translations or book distributors outside the U.S.A., please see the International Contact Information page immediately following the index of this book SQL Server™ 2000 Stored Procedure & XML Programming, Second Edition Copyright © 2003 by The McGraw-Hill Companies All rights reserved Printed in the United States of America Except as permitted under the Copyright Act of 1976, no part of this publication may be reproduced or distributed in any form or by any means, or stored in a database or retrieval system, without the prior written permission of publisher, with the exception that the program listings may be entered, stored, and executed in a computer system, but they may not be reproduced for publication 1234567890 CUS CUS 019876543 ISBN 0-07-222896-2 Publisher Vice President & Associate Publisher Acquisitions Editor Project Editor Acquisitions Coordinator Technical Editor Development Editor Copy Editor Proofreader Indexer Computer Designers Illustrators Series Designer Cover Series Designer Brandon A Nordin Scott Rogers Lisa McClain Janet Walden Athena Honore Deborah Bechtold Tom Woodhead William McManus Laurie Stewart Valerie Robbins Carie Abrew, Tara A Davis, Lucie Ericksen Lyssa Wald, Melinda Moore Lytle, Kathleen Fay Edwards Peter F Hancik Pattie Lee This book was composed with Corel VENTURA™ Publisher Information has been obtained by McGraw-Hill/Osborne from sources believed to be reliable However, because of the possibility of human or mechanical error by our sources, McGraw-Hill/Osborne, or others, McGraw-Hill/Osborne does not guarantee the accuracy, adequacy, or completeness of any information and is not responsible for any errors or omissions or the results obtained from the use of such information Writing a book isn’t easy, but living with someone who is writing a book can be, at times, even harder I would like to thank my family for their patience, understanding, and inspiration Acknowledgments I wish to thank all the people who helped to make this book a reality, in particular: Tom Woodhead, for straightening the winding course of my writings Olga Baranova, who created several examples for Chapters 10, 11, and 15 Wendy Rinaldi and Lisa McClain, for the opportunity to this project Athena Honore and Janet Walden, for their patience, expertise, and hard work Deborah Bechtold, for her expertise and hard work beyond the call of duty About the Author Dejan Šunderic is the principal consultant at Trigon Blue, Inc (www.trigonblue.com) He specializes in database and application development for Internet and Windows platforms Projects that he has been involved with cover B2C and B2B e-commerce, financial, document-management, mortgage, asset management, insurance, real-estate, IT supply chain, process control, communication, data warehouse, and OLAP systems Dejan has worked as a database architect, database and application developer, database administrator, team leader, project manager, writer, and technical trainer He is the author of SQL Server 2000 Stored Procedure Programming (www trigonblue.com/stored_procedure.htm), coauthor of Windows 2000 Performance Tuning and Optimization, and three other books, as well as numerous technical articles for several computer and professional publications His career started in Belgrade, Yugoslavia where he graduated on Faculty of Electrical Engineering In 1995 he moved to Toronto, Canada and he is currently in Pittsburgh, U.S.A He holds certifications for Microsoft Certified Solution Developer (MCSD), Microsoft Certified Database Administrator (MCDBA), and Certified SQL Server Programmer Master Level Dejan is a member of Toronto SQL Server User Group (www.tssug.com), Visual Basic Developer’s Online Group (www.visualbyte.com/vbdogs), Pittsburgh SQL Server User Group (www.pssug.com), and Professional Association for SQL Server (www.sqlpass.org) Dejan can be contacted by email (dejan’s username on hotmail.com server; to avoid spam filter, put sp_book in the subject) or the book’s web site (www trigonblue.com/sqlxml) Contents at a Glance Chapter Introduction Chapter The SQL Server Environment 19 Chapter Stored Procedure Design Concepts 53 Chapter Basic Transact-SQL Programming Constructs 85 Chapter Functions Chapter Composite Transact-SQL Constructs: Batches, Scripts, and Transactions 169 Chapter Debugging and Error Handling 207 Chapter Special Types of Procedures 259 Chapter Advanced Stored Procedure Programming 341 Chapter 10 Interaction with the SQL Server Environment 389 Chapter 11 Source Code Management and Database Deployment 437 Chapter 12 Stored Procedures for Web Search Engines 467 Chapter 13 Introduction to XML for Database Developers 489 Chapter 14 Publishing Information Using SQLXML 527 Chapter 15 Modifying Databases Using SQLXML 605 Appendix T-SQL and XML Data Types in SQL Server 2000 659 Index 131 669 v This page intentionally left blank Contents Chapter 1 Who Should Read This Book What You Will Find in This Book Requirements Stored Procedure Programming Requirements XML Programming Requirements Sample Database and Other Resources Sample Database Installation Purpose and Design of the Sample Database Database Diagram Chapter Introduction 3 5 6 10 The SQL Server Environment 19 SQL Server 2000 Tools Service Manager Query Analyzer Enterprise Manager DTS and Import/Export Data osql and isql SQL Server Profiler Client Network Utility Server Network Utility The Help Subsystem and SQL Server Books Online SQL Server on the Web Basic Operations with Stored Procedures What Are Stored Procedures? Execution of Stored Procedures from Query Analyzer Managing Stored Procedures from Enterprise Manager 20 21 22 24 26 27 27 28 29 29 30 31 31 32 36 vii viii SQL Server 2000 Stored Procedure & XML Programming Editing Stored Procedures in Enterprise Manager Editing Stored Procedures in Query Analyzer Syntax Errors Naming Conventions Why Bother? Naming Objects and Variables Suggested Convention Chapter 41 41 43 44 45 46 49 Stored Procedure Design Concepts 53 Anatomy of a Stored Procedure Composition Functionality Syntax Types of Stored Procedures Compilation The Compilation and Execution Process Reuse of Execution Plans Recompiling Stored Procedures Storing Stored Procedures Managing Stored Procedures Listing Stored Procedures Viewing Code of Stored Procedures Renaming Stored Procedures Deleting Stored Procedures Listing Dependent and Depending Objects The Role of Stored Procedures in the Development of Database Applications Enforcement of Data Integrity Consistent Implementation of Complex Business Rules and Constraints Modular Design Maintainability Reduced Network Traffic Faster Execution Enforcement of Security Chapter 54 54 57 64 65 67 67 68 71 72 74 75 77 79 79 80 82 82 83 83 83 84 84 84 Basic Transact-SQL Programming Constructs 85 T-SQL Identifiers Database Object Qualifiers 86 88 Contents Data Types Character Strings Unicode Character Strings Date and Time Data Types Integer Numbers Approximate Numbers Exact Numbers Monetary Data Types Binary Data Types Special Data Types Variables Local Variables Global Variables Table Variables Flow-Control Statements Comments Statement Blocks: Begin…End Conditional Execution: The If Statement Looping: The While Statement Unconditional Execution: The GoTo Statement Scheduled Execution: The WaitFor Statement Cursors Transact-SQL Cursors Cursor-Related Statements and Functions Problems with Cursors The Justified Uses of Cursors Chapter Functions 89 89 90 91 92 93 94 94 95 95 99 99 103 106 107 108 111 112 117 119 121 121 122 126 127 128 131 Using Functions In Selection and Assignment As Part of the Selection Criteria In Expressions As Check and Default Constraints Instead of Tables Types of Functions Scalar Functions Aggregate Functions Rowset Functions 132 132 133 133 134 134 135 136 164 165 ix 666 SQL Server 2000 Stored Procedure & XML Programming Data Type and Synonym Description Range Sample Constant n/a 1, 0, true, false decimal n/a Arbitrary precision (minimum 18) –2.45,3001021.212 decimal positive and negative numbers double Double-precision 64-bit floating-point m × 2^e +0, –, INF (infinity), –INF (negative infinity), NaN (not-a-number), ±m × 2^e (floating-point number where m