SQL Server 2000 Stored Procedure Programming phần 1 pps

50 277 0
SQL Server 2000 Stored Procedure Programming phần 1 pps

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Stored Procedure Programming DEJAN SUNDERIC TOM WOODHEAD Osborne/McGraw-Hill Berkeley New York St Louis San Francisco Auckland Bogotá Hamburg London Madrid Mexico City Milan Montreal New Delhi Panama City Paris São Paulo Singapore Sydney Tokyo Toronto Brought to you by ownSky! Copyright © 2001 by The McGraw-Hill Companies All rights reserved Manufactured in the United States of America Except as permitted under the United States 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 the publisher 0-07-213361-9 The material in this eBook also appears in the print version of this title: 0-07-212566-7 All trademarks are trademarks of their respective owners Rather than put a trademark symbol after every occurrence of a trademarked name, we use names in an editorial fashion only, and to the benefit of the trademark owner, with no intention of infringement of the trademark Where such designations appear in this book, they have been printed with initial caps McGraw-Hill eBooks are available at special quantity discounts to use as premiums and sales promotions, or for use in corporate training programs For more information, please contact George Hoare, Special Sales, at george_hoare@mcgraw-hill.com or (212) 904-4069 TERMS OF USE This is a copyrighted work and The McGraw-Hill Companies, Inc (“McGraw-Hill”) and its licensors reserve all rights in and to the work Use of this work is subject to these terms Except as permitted under the Copyright Act of 1976 and the right to store and retrieve one copy of the work, you may not decompile, disassemble, reverse engineer, reproduce, modify, create derivative works based upon, transmit, distribute, disseminate, sell, publish or sublicense the work or any part of it without McGraw-Hill’s prior consent You may use the work for your own noncommercial and personal use; any other use of the work is strictly prohibited Your right to use the work may be terminated if you fail to comply with these terms THE WORK IS PROVIDED “AS IS” McGRAW-HILL AND ITS LICENSORS MAKE NO GUARANTEES OR WARRANTIES AS TO THE ACCURACY, ADEQUACY OR COMPLETENESS OF OR RESULTS TO BE OBTAINED FROM USING THE WORK, INCLUDING ANY INFORMATION THAT CAN BE ACCESSED THROUGH THE WORK VIA HYPERLINK OR OTHERWISE, AND EXPRESSLY DISCLAIM ANY WARRANTY, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO IMPLIED WARRANTIES OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE McGraw-Hill and its licensors do not warrant or guarantee that the functions contained in the work will meet your requirements or that its operation will be uninterrupted or error free Neither McGraw-Hill nor its licensors shall be liable to you or anyone else for any inaccuracy, error or omission, regardless of cause, in the work or for any damages resulting therefrom McGraw-Hill has no responsibility for the content of any information accessed through the work Under no circumstances shall McGraw-Hill and/or its licensors be liable for any indirect, incidental, special, punitive, consequential or similar damages that result from the use of or inability to use the work, even if any of them has been advised of the possibility of such damages This limitation of liability shall apply to any claim or cause whatsoever whether such claim or cause arises in contract, tort or otherwise DOI: 10.1036/0072133619 Terms of Use Writing a book isn’t easy, but living with someone who is writing a book can be, at times, even harder We would like to thank our respective spouses for their patience, understanding, and inspiration: For Mirjana Sunderic and Ann(a) Fricker AT A GLANCE w 1 w 2 w 3 w 4 w 5 w Introduction Relational Database Concepts and the SQL Server Environment Stored Procedure Design Concepts Basic Transact-SQL Programming Constructs Functions 1 21 65 105 167 viii SQL Server 2000 Stored Procedure Programming w A w B T-SQL and XML Datatypes in SQL Server 2000 633 Solutions to the Exercises 641 w Index 715 CONTENTS Acknowledgments w 1 Introduction Who Should Read This Book What You Will Find in This Book Requirements New Features in SQL Server 2000 Improved Web Enablement Improved Scalability and Reliability Improved Development and Administration Environment Sample Database Sample Database Installation Purpose and Design of the Sample Database Database Diagram Summary 1 3 3 5 6 7 7 8 9 9 11 12 20 21 23 w 2 Relational Database Concepts and the SQL Server Environment Databases xvii ix Terms of Use x SQL Server 2000 Stored Procedure Programming Relational Databases Database Objects What Are Stored Procedures? SQL Server 2000 Tools Service Manager Query Analyzer Enterprise Manager DTS—Import and Export Data osql and isql SQL Server Profiler Client Network Utility The Help Subsystem and SQL Server Books Online Basic Operations with Stored Procedures Execution of Stored Procedures from Query Analyzer Managing Stored Procedures from Enterprise Manager Editing Stored Procedures in Enterprise Manager Editing Stored Procedures in Query Analyzer Syntax Errors The Create Stored Procedure Wizard Summary Exercises 23 23 32 32 33 34 36 39 40 41 41 43 44 44 49 54 54 57 59 63 64 w 3 Stored Procedure Design Concepts 65 66 66 70 78 79 81 81 82 86 88 90 90 93 95 96 96 99 99 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 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 Contents Consistent Implementation of Complex Business Rules and Constraints Modular Design Maintainability Reduced Network Traffic Faster Execution Enforcement of Security Summary Exercises w 4 Basic Transact-SQL Programming Constructs TSQL Identifiers Database Object Qualifiers Datatypes Groups of Datatypes Datatype Synonyms User-Defined Datatypes 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 Summary Exercises 99 100 100 101 101 101 102 103 105 106 110 111 111 123 123 124 125 129 133 134 135 139 140 145 148 152 153 154 158 160 161 163 164 w 5 Functions Using Functions In Selection and Assignment In Filtering Criteria In Expressions As Check and Default Constraints Instead of Tables 167 168 168 169 170 170 170 xi Chapter 2: Relational Database Concepts and the SQL Server Environment Query Analyzer is designed as an MDI application that can contain one or more Query windows Users can use Query windows to enter and execute a batch of Transact-SQL statements A Query window contains two major components: the Query pane and the Results pane (see Figure 2-1) The Query pane is a Transact-SQL syntax-sensitive editor Because it is syntax-sensitive, users can type Transact-SQL statements in the pane and Query Analyzer will color different code components such as keywords, variables, and literals using different colors The Results pane displays the result of the code executed in the Query pane Earlier versions of SQL Server displayed results only Object Browser Query pane Results pane Figure 2-1 Query Analyzer Query Analyzer toolbar 35 Chapter 2: Relational Database Concepts and the SQL Server Environment Console tree Figure 2-2 Details pane Enterprise Manager procedures, the Details pane will list the tables or stored procedures in the current database The behavior of the Details pane is quite similar to that of Windows Explorer If the user selects certain objects in the Console tree, such as a database or a server, the Details pane displays the taskpad—a complex report showing the state of the database or server that can also be used to manage the database or server (see Figure 2-3) Taskpads are implemented as HTML pages Activities can be initiated by clicking links within the taskpad 37 38 SQL Server 2000 Stored Procedure Programming Figure 2-3 The taskpad Enterprise Manager has been developed as a Microsoft Management Console (MMC) snap-in A snap-in is simply a program designed to run inside MMC Other Back Office server management tools can also run inside MMC This design is the reason there are two major toolbars within the Enterprise Manager interface The top one contains options to let the user control MMC and its snap-ins The lower one is the Enterprise Manager toolbar, and in it you will find menus and icons for administering servers and databases Before SQL Server 7.0, Enterprise Manager contained a query tool for executing SQL queries against a database You now have to launch Query Analyzer from the Tools menu As I mentioned earlier, SQL Mail service can be controlled from the Support Services node in Enterprise Manager (see Figure 2-4) 46 SQL Server 2000 Stored Procedure Programming Figure 2-9 Execution of stored procedures from Query Analyzer You can click the Messages tab to see whether SQL Server has returned any messages along with the result (such as the number of records, a warning, or an error) This stored procedure lists active processes on the current server and the login names of the users who started them 4 Select Query | Results in Text and then execute the query again (Query | Execute) Query Analyzer displays the resultset in the form of text Messages are mixed with resultsets in this case, which is the way in which Query Analyzer has always worked in past versions (see Figure 2-10) Chapter 2: Figure 2-10 Relational Database Concepts and the SQL Server Environment Results in Text NOTE: Before we continue, please ensure that you have installed the sample Asset database If you have not already installed it, go to Chapter 1 and follow the download and installation instructions You can also use Object Browser in Query Analyzer to list, execute, and edit stored procedures: 1 If the Object Browser is not already present on the screen, click Tools | Object Browser to display it (see Figure 2-11) 2 Open the node that contains the master database and then the node for that database’s stored procedures Right-click the stored procedure sp_who in the list Select Open from the 47 48 SQL Server 2000 Stored Procedure Programming Figure 2-11 The Object Browser pop-up menu Query Analyzer prompts you to specify parameters and execute the stored procedure: 50 SQL Server 2000 Stored Procedure Programming if you have never opened Enterprise Manager before, you will have to register the first server with which you will work: 2 Again, you need to provide the name of the server, your Login Name, and your Password You can accept default values for the Server Group and all other Options If the connection parameters are correct, Enterprise Manager will display a window for managing SQL Server 3 Click the + symbol to expand the SQL Server Group branch 4 Expand your server branch (again, click the + symbol) 5 Expand the Databases branch 6 Expand the Asset sample database 7 Click Stored Procedures and watch as a list of stored procedures is displayed in the Details pane (see Figure 2-13) Chapter 2: Figure 2-13 Relational Database Concepts and the SQL Server Environment The list of stored procedures in Enterprise Manager 8 In this list, find a stored procedure named prGetEqId If you right-click a stored procedure, a pop-up menu appears with options to let you perform operations such as deleting and renaming the stored procedure or creating a new stored procedure At this point, the most interesting option on this pop-up menu is the Properties option 9 Right-click the prGetEqId stored procedure, then select Properties on the pop-up menu The application will open a window to allow you to view and edit the stored procedure (see Figure 2-14) See the sidebar “The Structure of Stored Procedures” for more information NOTE: Don’t worry In the following chapters, we will give you detailed descriptions of all these objects and their components 51 52 SQL Server 2000 Stored Procedure Programming The Structure of Stored Procedures We will pause a minute to explain the structure of a stored procedure The prGetEqId stored procedure encapsulates a relatively simple Select statement for later use It returns a recordset containing values from the EquipmentId column The recordset will contain only records with the specified Make and Model The code of a stored procedure consists of a header and a body The header of the stored procedure defines external attributes of the stored procedure—its name and a list of one or more parameters The prGetEqId stored procedure has two parameters Parameter names must start with the @ character The developer must also define a datatype for each parameter The header must begin with the Create Procedure keyword and finish with the As keyword The body of the stored procedure contains the Transact-SQL statements to be executed when the stored procedure runs In this case, there is just one Select statement using the procedure parameters Figure 2-14 Properties of a stored procedure Chapter 2: Relational Database Concepts and the SQL Server Environment 10 Close the Properties window 11 Right-click any stored procedure in the list and select New Stored Procedure from the pop-up menu Enterprise Manager displays a Properties window with a template for the stored procedure (see Figure 2-15) 12 Replace the template with the following code: Create procedure prHelloWorld_1 As Select 'Hello world' Select * from Inventory 13 Click the Check Syntax button to verify the syntax of the procedure 14 Click OK The procedure is compiled and stored in the database You will be able to see it in the list of stored procedures Figure 2-15 A template for the New Stored Procedure 53 Chapter 2: Relational Database Concepts and the SQL Server Environment Traditionally, DBAs included the code for deleting (dropping) the original stored procedure and then recreating the stored procedure (with the changed code): 1 Launch Query Analyzer 2 Make sure that you are in the Asset database 3 Type the following code in the Query pane: Drop procedure prHelloWorld_1 Go Create procedure prHelloWorld_1 As Select 'Hello Dejan' select * from Inventory Return 0 Go 4 Execute the code by selecting Execute on the Query menu SQL Server will first delete the existing stored procedure and then recreate it (with the new code) The trouble with this method (dropping and then recreating) is that you also drop some attributes associated with the stored procedure (such as permissions), which also affects other dependent objects Since Microsoft SQL Server 7.0, it is possible to use the Alter Procedure statement to modify an existing stored procedure without affecting permissions and other dependent objects: Alter Procedure prHelloWorld_1 As Select 'Hello World again!' Select * from Inventory Return 0 Go You may have noticed the Go command in the previous two examples This command is not a SQL statement It is not even part 55 56 SQL Server 2000 Stored Procedure Programming of the TSQL language It is a signal to Query Analyzer (and some other tools, such as isql and osql) to treat the SQL statements as one set—a batch All statements in a batch are compiled and executed together In SQL Server 2000, it is possible to use Object Browser to edit stored procedures: 1 If the Object Browser is not already present on the screen, select Tools | Object Browser to display it 2 Open the Asset database and then its list of stored procedures 3 Find and right-click prHelloWorld_1 in the list Select Edit from the pop-up menu, and Query Analyzer displays a Query window with the code of the stored procedure in it (see Figure 2-16) Figure 2-16 The Query window displays the stored procedure’s code 58 SQL Server 2000 Stored Procedure Programming Figure 2-17 An error in Query Analyzer TIP: If you double-click the error message in the Result pane, Query Analyzer returns the cursor to the line containing the error in the Query pane (most of the time) This is very useful when you are executing a long batch Another advantage the Alter statement has over the Drop/Create approach is that the stored procedure remains intact after an unsuccessful attempt such as we produced in this example 2 You can cancel the changes or remove the dashes and attempt execution again ... 99 10 0 10 0 10 1 10 1 10 1 10 2 10 3 10 5 10 6 11 0 11 1 11 1 12 3 12 3 12 4 12 5 12 9 13 3 13 4 13 5 13 9 14 0 14 5 14 8 15 2 15 3 15 4 15 8 16 0... 3 71 372 374 382 384 385 386 3 91 395 398 399 406 408 xiii xiv SQL Server 2000 Stored Procedure Programming w 10 Advanced Stored Procedure Programming 409 410 410 412 415 ... 16 7 16 8 16 8 16 9 17 0 17 0 17 0 xi xii SQL Server 2000 Stored Procedure Programming Types of Functions Scalar Functions Aggregate

Ngày đăng: 13/08/2014, 08:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan