Lab Answer Key for Module 8: Implementing Stored Procedures Table of Contents Lab 8: Implementing Stored Procedures 1 Exercise 1: Creating Stored Procedures 1 Exercise 2: Working with Execution Plans 6
Information in this document, including URL and other Internet Web site references, is subject to change without notice. Unless otherwise noted, the example companies, organizations, products, domain names, e- mail addresses, logos, people, places, and events depicted herein are fictitious, and no association with any real company, organization, product, domain name, e-mail address, logo, person, place, or event is intended or should be inferred. Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or otherwise), or for any purpose, without the express written permission of Microsoft Corporation. The names of manufacturers, products, or URLs are provided for informational purposes only and Microsoft makes no representations and warranties, either expressed, implied, or statutory, regarding these manufacturers or the use of the products with any Microsoft technologies. The inclusion of a manufacturer or product does not imply endorsement of Microsoft of the manufacturer or product. Links are provided to third party sites. Such sites are not under the control of Microsoft and Microsoft is not responsible for the contents of any linked site or any link contained in a linked site, or any changes or updates to such sites. Microsoft is not responsible for webcasting or any other form of transmission received from any linked site. Microsoft is providing these links to you only as a convenience, and the inclusion of any link does not imply endorsement of Microsoft of the site or the products contained therein. Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property rights covering subject matter in this document. Except as expressly provided in any written license agreement from Microsoft, the furnishing of this document does not give you any license to these patents, trademarks, copyrights, or other intellectual property. 2007 Microsoft Corporation. All rights reserved. Microsoft, BizTalk, Internet Explorer, Jscript, MSDN, Outlook, PowerPoint, SQL Server, Visual Basic, Visual C#, Visual C++, Visual FoxPro, Visual Studio, Windows and Windows Server are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. Version 1.0
Lab Answer Key for Module 8: Implementing Stored Procedures 1 Lab 8: Implementing Stored Procedures Exercise 1: Creating Stored Procedures Task 1: Create and test the GetDiscounts stored procedure 1. Click Start, point to All Programs, point to Microsoft SQL Server 2005, and then click SQL Server Management Studio. 2. In the Connect to Server dialog box, specify the values in the following table, and then click Connect. Property Server type Server name Authentication Value Database Engine MIAMI Windows Authentication 3. On the File menu, point to Open, and then click Project/Solution. 4. In the Open Project dialog box, browse to the D:\Labfiles\Starter folder, click the AWProgrammability.ssmssln solution, and then click Open. 5. If Solution Explorer is not visible, on the View menu, click Solution Explorer. 6. In Solution Explorer, expand AWProgrammability, expand Queries, and then double-click the InitializeData.sql query file. 7. On the toolbar, click Execute, and then confirm that no errors occur. 8. In Solution Explorer, double-click the StoredProcedures.sql query file. 9. Select the USE AdventureWorks statement, and then on the toolbar, click Execute. 10. Locate the Create Sales.GetDiscounts comment, and then create the stored procedure, as shown in the following Transact-SQL example. CREATE PROCEDURE Sales.GetDiscounts AS SELECT Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty FROM Sales.SpecialOffer ORDER BY StartDate, EndDate 11. Select the CREATE PROCEDURE statement, and then on the toolbar, click Execute. 12. Review the query results and verify that the statement executed successfully.
2 Lab Answer Key for Module 8: Implementing Stored Procedures 13. Locate the Test Sales.GetDiscounts comment, and then type in a statement to test the stored procedure, as shown in the following Transact-SQL example. EXEC Sales.GetDiscounts 14. Select the EXEC statement, and then on the toolbar, click Execute. 15. In the query results, verify that several rows are displayed. 16. On the File menu, click Save StoredProcedures.sql. 17. Keep the Microsoft SQL Server Management Studio solution open. You will use it in the next task. Task 2: Create and test the GetDiscountsForCategory stored procedure 1. Locate the Create Sales.GetDiscountsForCategory comment, and then create the stored procedure, as shown in the following Transact-SQL example. CREATE PROCEDURE Sales.GetDiscountsForCategory @Category nvarchar(50) AS SELECT Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty FROM Sales.SpecialOffer WHERE Category = @Category ORDER BY StartDate, EndDate 2. Select the CREATE PROCECURE statement, and then on the toolbar, click Execute. 3. Review the query results and verify that the statement executed successfully. 4. Locate the Test Sales.GetDiscountsForCategory comment, and then type in a statement to test the stored procedure, as shown in the following Transact-SQL example. EXEC Sales.GetDiscountsForCategory 'Reseller' 5. Select the EXEC statement, and then on the toolbar, click Execute. 6. In the query results, verify that 13 rows are displayed. 7. On the File menu, click Save StoredProcedures.sql. 8. Keep the SQL Server Management Studio solution open. You will use it in the next task.
Lab Answer Key for Module 8: Implementing Stored Procedures 3 Task 3: Create and test the GetDiscountsForCategoryAndDate stored procedure 1. Locate the Create Sales.GetDiscountsForCategoryAndDate comment, and then create the stored procedure, as shown in the following Transact-SQL example. CREATE PROCEDURE Sales.GetDiscountsForCategoryAndDate @Category nvarchar(50), @DateToCheck datetime = NULL AS IF (@DateToCheck IS NULL) SET @DateToCheck = GetDate() SELECT Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty FROM Sales.SpecialOffer WHERE Category = @Category AND @DateToCheck BETWEEN StartDate AND EndDate ORDER BY StartDate, EndDate 2. Select the CREATE PROCEDURE statement, and then on the toolbar, click Execute. 3. Review the query results and verify that the statement executed successfully. 4. Locate the Test Sales.GetDiscountsForCategoryAndDate with category but no date comment, and then type in a statement to test the stored procedure, as shown in the following Transact-SQL example. EXEC Sales.GetDiscountsForCategoryAndDate 'Reseller' 5. Select the EXEC statement, and then on the toolbar, click Execute. 6. In the query results, verify that six rows are displayed. This is the current list of discounts, because the @DateToCheck parameter defaults to the current date and time. 7. Locate the Test Sales.GetDiscountsForCategoryAndDate with both parameters comment, and then type in statements to test the stored procedure, as shown in the following Transact-SQL example. DECLARE @DateToCheck datetime SET @DateToCheck = DateAdd(month, 1, GetDate()) EXEC Sales.GetDiscountsForCategoryAndDate 'Reseller', @DateToCheck 8. Select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. 9. In the query results, verify that seven rows are displayed. This is the list of discounts that will be current in one month s time.
4 Lab Answer Key for Module 8: Implementing Stored Procedures 10. On the File menu, click Save StoredProcedures.sql. 11. Keep the SQL Server Management Studio solution open. You will use it in the next task. Task 4: Create and test the AddDiscount stored procedure 1. Locate the Create Sales.AddDiscount comment, and then create the stored procedure, as shown in the following Transact-SQL example. CREATE PROCEDURE Sales.AddDiscount @Description nvarchar(255), @DiscountPct smallmoney, @Type nvarchar(50), @Category nvarchar(50), @StartDate datetime, @EndDate datetime, @MinQty int, @MaxQty int, @NewProductID int OUTPUT AS BEGIN TRY INSERT Sales.SpecialOffer (Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty) VALUES (@Description, @DiscountPct, @Type, @Category, @StartDate, @EndDate, @MinQty, @MaxQty) SET @NewProductID = SCOPE_IDENTITY() RETURN 0 END TRY BEGIN CATCH INSERT dbo.errorlog (UserName, ErrorNumber, ErrorSeverity, ErrorState, ErrorProcedure, ErrorLine, ErrorMessage) VALUES (CONVERT(sysname, CURRENT_USER), ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), ERROR_LINE(), ERROR_MESSAGE() ) RETURN -1 END CATCH 2. Select the CREATE PROCEDURE statement, and then on the toolbar, click Execute. 3. Review the query results and verify that the statement executed successfully. 4. Locate the Test Sales.AddDiscount comment, and then type in statements to test the stored procedure, as shown in the following Transact-SQL example. DECLARE @StartDate datetime, @EndDate datetime SET @StartDate = GetDate() SET @EndDate = DateAdd(month, 1, @StartDate) DECLARE @NewId int EXEC Sales.AddDiscount 'Half price off everything',
Lab Answer Key for Module 8: Implementing Stored Procedures 5 0.5, 'Seasonal Discount', 'Customer', @StartDate, @EndDate, 0, 20, @NewID OUTPUT SELECT @NewID 5. Select the DECLARE, SET, EXEC, and SELECT statements, and then on the toolbar, click Execute. 6. In the query results, verify that a new SpecialOfferID is returned. 7. Locate the Test Sales.AddDiscount with errors comment, and then type in statements to test the stored procedure again, as shown in the following Transact- SQL example. DECLARE @StartDate datetime, @EndDate datetime SET @StartDate = GetDate() SET @EndDate = DateAdd(month, 1, @StartDate) DECLARE @NewId int, @ReturnValue int EXEC @ReturnValue = Sales.AddDiscount 'Half price off everything', -0.5, -- UNACCEPTABLE VALUE 'Seasonal Discount', 'Customer', @StartDate, @EndDate, 0, 20, @NewID OUTPUT IF (@ReturnValue = 0) SELECT @NewID ELSE SELECT TOP 1 * FROM dbo.errorlog ORDER BY ErrorTime DESC 8. Select the DECLARE, SET, EXEC, and IF/ELSE statements, and then on the toolbar, click Execute. 9. In the query results, confirm that an error record is displayed that includes the ErrorProcedure value AddDiscount. 10. On the File menu, click Save StoredProcedures.sql.. 11. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
6 Lab Answer Key for Module 8: Implementing Stored Procedures Exercise 2: Working with Execution Plans Task 1: View the text-based execution plans 1. In Solution Explorer, double-click the Setup.sql query file. 2. On the toolbar, click Execute, and then confirm that no errors occur. 3. In Solution Explorer, double-click the ExecutionPlans.sql query file. 4. Locate the SET statement options comment, and then add the following SET statement option. SET STATISTICS PROFILE ON 5. On the toolbar, click Execute, and then review the actual execution plan generated for each query batch. 6. Keep the SQL Server Management Studio solution open. You will use it in the next task. Task 2: View the graphical execution plans 1. Locate the SET statement you created in the previous task. Amend the SET statement to turn off the generation of text-based execution plans. SET STATISTICS PROFILE OFF 2. Select this statement, and then on the toolbar, click Execute. 3. Confirm that the statement executed successfully, and then delete the statement. 4. On the toolbar, click the Include Actual Execution Plan button, click the Include Client Statistics button, and then click Execute. 5. Click the Execution plan tab to review the graphical execution plan for each query batch, paying particular attention to the warnings and looking for table scans, sorts, and other indicators of potential performance issues. 6. On the Client Statistics tab, note the query execution statistics. 7. Keep the SQL Server Management Studio solution open. You will use it in the next task. Task 3: Tune the database to improve performance 1. In Solution Explorer, double-click the DatabaseTuning.sql query file. 2. On the toolbar, click Execute, and then confirm that no errors occur. 3. Keep the SQL Server Management Studio solution open. You will use it in the next task.
Lab Answer Key for Module 8: Implementing Stored Procedures 7 Task 4: View the revised execution plans 1. In Solution Explorer, double-click the ExecutionPlans.sql query file. 2. Ensure that the Include Actual Execution Plan and Include Client Statistics buttons on the toolbar are both still selected. 3. On the toolbar, click Execute. 4. Click the Execution plan tab to review the graphical execution plan for each query batch and note the differences from the original execution plan. 5. Click the Client Statistics tab and note the query execution statistics that show the performance improvement. 6. Close SQL Server Management Studio without saving the changes to the files.