Documentos de Académico
Documentos de Profesional
Documentos de Cultura
M I C R O S O F T
L E A R N I N G
P R O D U C T
6232B
Lab Instructions and Lab Answer Key: Implementing a Microsoft SQL Server 2008 R2 Database
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. 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. 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 may be 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. 2011 Microsoft Corporation. All rights reserved. Microsoft, and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. All other trademarks are property of their respective owners.
Module 1
Lab Instructions: Introduction to SQL Server 2008 R2 and its Toolset
Contents:
Exercise 1: Verify SQL Server Component Installation Exercise 2: Alter Service Accounts for New Instance Exercise 3: Enable Named Pipes Protocol for Both Instances Exercise 4: Create Aliases for AdventureWorks and Proseware Challenge Exercise 5: Ensure SQL Browser is Disabled and Configure a Fixed TCP/IP Port (Only if time permits) 4 5 6 7 8
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V window. In the Virtual Machines list, right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, then close the Virtual Machine Connection window. 6. In Hyper-V Manager, in the Virtual Machines list, right-click 623XB-MIA-SQL1 and click Start. 7. Right-click 623XB-MIA-SQL1 and click Connect. 8. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears. 9. On the Action menu, click the Ctrl+Alt+Delete menu item. 10. Click Switch User, then click Other User. 11. Log on using the following credentials: 1. 2. 3. 4. 5. User name: AdventureWorks\Administrator Password: Pa$$w0rd
12. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 13. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
Lab Scenario
AdventureWorks is a global manufacturer, wholesaler and retailer of cycle products. The owners of the company have decided to start a new direct marketing arm of the company. It has been created as a new company named Proseware, Inc. Even though it has been set up as a separate company, it will receive
some IT-related services from the existing AdventureWorks company and will be provided with a subset of the corporate AdventureWorks data. The existing AdventureWorks company SQL Server platform has been moved to a new server that is capable of supporting both the existing workload and the workload from the new company. In this lab, you are ensuring that the additional instance of SQL Server has been configured appropriately and making a number of additional required configuration changes.
Task 1: Check that Database Engine and Reporting Services have been installed for the
MKTG instance
Open SQL Server Configuration Manager. Check the installed list of services for the MKTG instance and ensure that the database engine and Reporting Services have been installed for the MKTG instance.
Task 2: Note the services that are installed for the default instance and that Integration
Services is not installed on a per instance basis
Note the list of services that are installed for the default instance. Note that Integration Services has no instance name shown as it is not installed on a per-instance basis.
Task 3: Ensure that all required services including SQL Server Agent are started and set
to autostart for both instances
Ensure that all the MKTG services are started and set to autostart. (Ignore the Full Text Filter Daemon at this time). Ensure that all the services for the default instance are set to autostart. (Ignore the Full Text Filter Daemon at this time). Results: After this exercise, you have checked that the required SQL Server services are installed, started, and configured to autostart.
Task 1: Change the service account for the MKTG database engine
Change the service account for the MKTG database engine service to AdventureWorks\PWService using the properties page for the service.
Task 2: Change the service account for the MKTG SQL Server Agent
Change the service account for the MKTG SQL Server Agent service to AdventureWorks\PWService using the properties page for the service and then restart the service. Results: After this exercise, you have configured the service accounts for the MKTG instance.
Task 1: Enable the named pipes protocol for the default instance
Enable the named pipes protocol for the default database engine instance using the Protocols window.
Task 2: Enable the named pipes protocol for the MKTG instance
Enable the named pipes protocol for the MKTG database engine instance using the Protocols window.
Task 5: Use SQL Server Management Studio to connect to both aliases to ensure they
work as expected
Open SQL Server Management Studio. Connect to the Proseware alias. In Object Explorer, connect also to the AdventureWorks alias. Results: After this exercise, you should have created and tested aliases for both database engine instances.
Challenge Exercise 5: Ensure SQL Browser is Disabled and Configure a Fixed TCP/IP Port (Only if time permits)
Scenario
Client applications will need to connect to the MKTG database engine instance via the TCP/IP protocol. As their connections will need to traverse a firewall, the port used for connections cannot be configured as a dynamic port. The port number must not change. Corporate policy at AdventureWorks is that named instances should be accessed via fixed TCP ports and the SQLBrowser service should be disabled. In this exercise, you will make configuration changes to comply with these requirements. A firewall exception has already been created for port 51550, for use with the MKTG database engine instance. The main tasks for this exercise are as follows: 1. Configure the TCP port for the MKTG database engine instance to 51550. Disable the SQLBrowser service.
Task 1: Configure the TCP port for the MKTG database engine instance to 51550
Using the property page for the TCP/IP server protocol, configure the use of the fixed port 51550. (Make sure that you clear the dynamic port) Restart the MKTG database engine instance. Ensure that the MKTG database engine instance has been restarted successfully.
Module 2
Lab Instructions: Working with Data Types
Contents:
Exercise 1: Choosing Appropriate Data Types Exercise 2: Writing Queries With Data Type Conversions Challenge Exercise 3: Designing and Creating Alias Data Types (Only if time permits) 6 7 8
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item.
Click Switch User, and then click Other User. Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
A new developer has sought your assistance in deciding which data types to use for three new tables she is designing. She presents you with a list of organizational data requirements for each table. You need to decide on appropriate data types for each item. You also need to export some data from your existing system but while being exported, some of the columns need to be converted to alternate data types. If you have time, there is another issue that your manager would like you to address. She is concerned about a lack of consistency in the use of data types across the organization. At present, she is concerned about email addresses and phone numbers. You need to review the existing data types being used in the MarketDev database for this and create new data types that can be used in applications, to avoid this inconsistency.
Supporting Documentation
Table 1: PhoneCampaign Description Which campaign this relates to. The prospect that was contacted. When contact was first attempted with the prospect. Comments related to the contact that was made, if it was made.
When contact was actually made with the prospect. Outcome of the contact: sale, later follow-up, or no interest Value of any sale made (up to 2 decimal places)
Table 2: Opportunity Description Name of the opportunity Which prospect this opportunity relates to Stage the sale is at: Lead, Qualification, Proposal Development, Contract Negotiations, Complete, Lost Date that the opportunity was raised Probability of success Rating: Cold, Warm, Hot Estimated closing date Estimated revenue Delivery address
Table 3: SpecialOrder Description Which prospect this order is for External supplier of the item Description of the item Quantity Required (some quantities are whole numbers, some are fractional with up to three decimal places) Date of order Promised delivery date
Actual delivery date Special requirements (any comments related to the special order) Quoted price per unit (up to two decimal places)
Query Requirement 1: A list of products from the Marketing.Product table that are no longer sold, that is they have a SellEndDate. The output should show ProductID, ProductName, and SellEndDate formatted as a string based on the following format: YYYYMMDD. The output should appear similar to:
Query Requirement 2: A list of products from the Marketing.Product table that have demographic information. The output should show ProductID, ProductName, and Demographics formatted as nvarchar(1000) instead of XML. The output should appear similar to:
1.
3.
Task 2: Review the first query requirement and write a SELECT statement to meet the
requirement
Review the supporting documentation for details for the first query requirement. Write a SELECT statement that returns the required data. The output should look similar to the supplied sample.
Task 3: Review the second query requirement and write a SELECT statement to meet the
requirement
Review the supporting documentation for details for the second query requirement. Write a SELECT statement that returns the required data. The output should look similar to the supplied sample. Results: After this exercise, you should have created two new SELECT statements as per the design requirements.
Challenge Exercise 3: Designing and Creating Alias Data Types (Only if time permits)
Scenario
In this exercise, your manager is concerned about a lack of consistency in the use of data types across the organization. At present, she is concerned about email addresses and phone numbers. You need to review the existing data types being used in the MarketDev database for this and create new data types that can be used in applications, to avoid this inconsistency. The main tasks for this exercise are as follows: 1. 2. 3. Investigate the storage of phone numbers and email addresses Create a data type to be used to store phone numbers Create a data type to be used to stored email addresses
Module 3
Lab Instructions: Designing and Implementing Tables
Contents:
Exercise 1: Improve the Design of Tables Exercise 2: Create a Schema Challenge Exercise 3: Create the Tables (Only if time permits) 6 7 8
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item.
Click Switch User, and then click Other User. Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_03_PRJ\6232B_03_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
A business analyst from your organization has provided you with a first-pass at a schema design for some new tables being added to the MarketDev database. You need to provide an improved schema design based on good design practices and an appropriate level of normalization. The business analyst was also confused about when data should be nullable. You need to decide about nullability for each column in your improved design. The new tables need to be isolated in their own schema. You need to create the required schema DirectMarketing. The owner of the schema should be dbo. When the schema has been created, if you have available time, you need to create the tables that have been designed.
Name Comments Table2: TVAdvertisement Name TV_Station City CostPerAdvertisement TotalCostOfAllAdvertisements NumberOfAdvertisements Date_Of_Advertisement_1 Time_Of_Advertisement_1 Date_Of_Advertisement_2 Time_Of_Advertisement_2 Date_Of_Advertisement_3 Time_Of_Advertisement_3 Date_Of_Advertisement_4 Time_Of_Advertisement_4 Date_Of_Advertisement_5 Time_Of_Advertisement_5 Table3: Campaign_Response Name ResponseOccurredWhen RelevantProspect RespondedHow ChargeFromReferrer RevenueFromResponse
Data Type nvarchar(15) nvarchar(25) float float varchar(4) varchar(12) int varchar(12) int varchar(12) int varchar(12) int varchar(12) int
Data Type datetime int varchar(8) (phone, email, fax, letter) float float
Name ResponseProfit
1.
Module 4
Lab Instructions: Designing and Implementing Views
Contents:
Exercise 1: Design, Implement and Test the WebStock Views Exercise 2: Design and Implement the Contacts View Challenge Exercise 3: Modify the AvailableModels View (Only if time permits) 5 6 7
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item.
Click Switch User, and then click Other User. Log on using the following credentials: i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_04_PRJ\6232B_04_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
A new web-based stock promotion system is being rolled out. Your manager is very concerned about providing access from the web-based system directly to the tables in your database. She has requested you to design some views that the web-based system could connect to instead. Details of organizational contacts are held in a number of tables. The relationship management system being used by the account management team needs to be able to gain access to these contacts. However, they need a single view that comprises all contacts. You need to design, implement and test the required view. Finally, if you have time, a request has been received from the new Marketing team that the catalog description of the product models should be added to the AvailableModels view. They would appreciate you modifying the view to provide this additional column.
Supporting Documentation
View1: OnlineProducts ViewColumn ProductID ProductName ProductNumber Color Availability SourceColumn ProductID ProductName ProductNumber Color (note N/A should be returned when NULL) Based on DaysToManufacture (0 = Instock, 1 = Overnight, 2 = Fast, Other Values = Call)
Note: Based on table Marketing.Product. Rows should only appear if the product has begun to be sold and is still being sold. (Derive this from SellStartDate and SellEndDate). View2: AvailableModels ViewColumn ProductID ProductName ProductModelID ProductModel SourceColumn ProductID ProductName ProductModelID ProductModel
Based on tables Marketing.Product and Marketing.ProductModel. Rows should only appear if the product has at least one model, has begun to be sold and is still being sold. (Derive this from SellStartDate and SellEndDate). View3: Contacts ViewColumn ContactID FirstName MiddleName LastName ContactRole SourceColumn in Prospect ProspectID FirstName MiddleName LastName PROSPECT Source Column in Salesperson SalespersonID FirstName MiddleName LastName SALESPERSON
4.
Module 5
Lab Instructions: Planning for SQL Server 2008 R2 Indexing
Contents:
Exercise 1: Explore existing index statistics 5 Challenge Exercise 2: Design column orders for indexes (Only if time permits) 7
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item.
Click Switch User, and then click Other User. Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_05_PRJ\6232B_05_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
You have been asked to explain the concept of index statistics and selectivity to a new developer. You will explore the statistics available on an existing index and determine how selective some sample queries would be. One of the company developers has provided you with a list of the most important queries that will be executed by the new marketing management system. Depending upon how much time you have available, you need to determine the best column orders for indexes to support each query. Complete as many as possible within the allocated time. In later modules, you will consider how these indexes would be implemented. Each query is to be considered in isolation in this exercise.
Supporting Documentation
Query 1:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE ProspectID = 12553;
Query 2:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Arif%';
Query 3:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Alejandro%'
Query 4:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName >= 'S' ORDER BY LastName, FirstName;
Query 5:
SELECT LanguageID, COUNT(1) FROM Marketing.ProductDescription GROUP BY LanguageID;
2. 3. 4. 5. 6.
Review the results. Have any autostats been generated? Create manual statistics on the Color column. Call the statistics Product_Color_Stats. Use a full scan of the data when creating the statistics. Re-execute the command from task 1 to see the change. Using the DBCC SHOW_STATISTICS command, review the created Product_Color_Stats statistics. Answer the following questions related to the Product_Color_Stats statistics: a. b. c. d. How many rows were sampled? How many steps were created? What was the average key length? How many Black products are there?
7.
Execute the following command to check how accurate the statistics that have been generated are:
8.
Calculate the selectivity of each of the three queries shown: a) b) c) SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'A%'; SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Alejandro%'; SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Arif%';
Query 2:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Alejandro%';
Query 3:
SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Arif%';
Results: After this exercise, you have assessed Selectivity on each various queries.
Challenge Exercise 2: Design column orders for indexes (Only if time permits)
Scenario
One of the company developers has provided you with a list of the most important queries that will be executed by the new marketing management system. You need to determine the best column orders for indexes to support each query. In later modules, you will consider how these indexes would be implemented. Each query is to be considered in isolation in this exercise. The main tasks for this exercise are as follows: 1. 2. 3. 4. 5. Determine which columns should be part of an index for Query1 and the best order for the columns to support the query. Determine which columns should be part of an index for Query2 and the best order for the columns to support the query. Determine which columns should be part of an index for Query3 and the best order for the columns to support the query. Determine which columns should be part of an index for Query4 and the best order for the columns to support the query. Determine which columns should be part of an index for Query5 and the best order for the columns to support the query.
Module 6
Lab Instructions: Implementing Table Structures in SQL Server 2008 R2
Contents:
Exercise 1: Creating Tables as Heaps Exercise 2: Creating Tables with Clustered Indexes Challenge Exercise 3: Comparing the Performance of Clustered Indexes vs. Heaps (Only if time permits) 5 6 7
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item.
Click Switch User, and then click Other User. Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
One of the most important decisions when designing a table is to choose an appropriate table structure. In this lab, you will choose an appropriate structure for some new tables required for the relationship management system.
Supporting Documentation
Table 1: Relationship.ActivityLog Name ActivityTime SessionID Duration ActivityType Table 2: Relationship.PhoneLog Name PhoneLogID SalespersonID CalledPhoneNumber CallDurationSeconds Data Type int int nvarchar(16) int Constraint Primary Key Data Type datetimeoffset int int int Constraint
Table 3: Relationship.MediaOutlet Name MediaOutletID MediaOutletName PrimaryContact City Data Type int nvarchar(40) nvarchar(50) nvarchar(50) Constraint
Table 4: Relationship.PrintMediaPlacement Name PrintMediaPlacementID MediaOutletID PlacementDate PublicationDate RelatedProductID PlacementCost Table 5: Name ApplicationID ApplicantName EmailAddress ReferenceID Comments Data Type int nvarchar(150) nvarchar(100) uniqueidentifier nvarchar(500) Constraint IDENTITY(1,1) Data Type int int datetime datetime int decimal(18,2) Constraint Primary Key
Challenge Exercise 3: Comparing the Performance of Clustered Indexes vs. Heaps (Only if time permits)
Scenario
A company developer has approached you to decide whether a new table should have a clustered index or not. Insert performance of the table is critical. You will consider the design, create a number of alternatives and compare the performance of each against a set of test workloads. The main tasks for this exercise are as follows: 1. 2. 3. 4. 5. 6. Review the Design for Table 5. Create a table based on the design with no clustered index. Call the table Relationship.Table_Heap. Create a table based on the design with a clustered index on the ApplicantID column. Call the table Relationship.Table_ApplicationID. Create a table based on the design with a clustered index on the EmailAddress column. Call the table Relationship.Table_EmailAddress. Create a table based on the design with a clustered index on the ReferenceID column. Call the table Relationship.Table_ReferenceID. Load and execute the workload script. (Note: this may take some minutes to complete. You can check where it is up to by viewing the Messages tab. A message is printed as each of the four sections is completed. While the script is running, review the contents of the script and estimate the proportion of time difference you expect to see in the results). Compare the performance of each table structure.
7.
Module 7
Lab Instructions: Reading SQL Server 2008 R2 Execution Plans
Contents:
Exercise 1: Actual vs. Estimated Plans Exercise 2: Identify Common Plan Elements Challenge Exercise 3: Query Cost Comparison (Only if time permits) 4 6 8
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item.
Click Switch User, and then click Other User. Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
You have been learning about the design of indexes. To take this learning further, you need to have a way to view how these indexes are used. In the first exercise, you will learn to view both estimated and actual execution plans. Execution plans can contain many types of elements. In the second exercise, you will learn to identify the most common plan elements and see how statements lead to these elements being used. You regularly find yourself trying to decide between different ways of structuring SQL queries. You are concerned that you arent always choosing the highest-performing options. If time permits, you will learn to use execution plans to compare the cost of statements in multi-statement batches.
Task 3: View the estimated execution plan for script 7.2 using SHOWPLAN_XML
Execute script 7.2 in SQL Server Query Analyzer. Click on the returned XML and view the execution plan. Right-click in the whitespace in the plan. Choose Show Execution Plan XML. Briefly review the XML. Close the XML window and the execution plan window.
Task 7: Review the execution plans currently cached in memory using script 7.5
Execute script 7.5 to view the plans currently cached in memory
Results: After this exercise, you have reviewed various actual and estimated query plans.
Task 10: Explain the actual execution plan from script 7.14
Execute script 7.14. Note the difference in this plan from the plan for script 7.12. Results: After this exercise, you will have analyzed the most common plan elements returned from queries.
Module 8
Lab Instructions: Improving Performance through Nonclustered Indexes
Contents:
Exercise 1: Nonclustered index usage review Exercise 2: Improving nonclustered index designs Exercise 3: SQL Server Profiler and Database Engine Tuning Advisor Challenge Exercise 4: Nonclustered index design (Only if time permits) 5 6 7 8
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
The marketing system includes a query that is constantly executed and is performing too slowly. It retrieves 5000 web log entries beyond a given starting time. Previously, a non-clustered index was created on the SessionStart column. When 100 web log entries were being retrieved at a time, the index was being used. The developer is puzzled that changing the request to 5000 entries at a time has caused SQL Server to ignore the index he built. You need to investigate the query and suggest the best non-clustered index to support the query. You will then test your suggestion. After you have created the new index, the developer noted the cost of the sort operation and tried to create another index that would eliminate the sort. You need to explain to him why SQL Server has decided not to use this index. Later you will learn to set up a basic query tuning trace in SQL Server Profiler and use the trace captured in Database Engine Tuning Advisor. If time permits, you will design a required nonclustered index.
Supporting Documentation
Query 1: Query to test
DECLARE @StartTime datetime2 = '2010-08-30 16:27'; SELECT TOP(5000) wl.SessionID, wl.ServerID, wl.UserName FROM Marketing.WebLog AS wl WHERE wl.SessionStart >= @StartTime ORDER BY wl.SessionStart, wl.ServerID;
4.
Task 3: Test the design and explain why the index was not used
Enable Include Actual Execution Plan. Execute the query. Review the Execution Plan and explain why the index was not used. Results: After this exercise, you have understood why some indexes are not appropriate in some scenerios.
Task 3: Design a more appropriate index by following the Missing Index suggestion
Review and implement the Missing Index that SQL Server has suggested. Test to ensure that the new index is being used.
Task 4: Create a better index that removes the sort operation. If you create another
index, confirm that SQL Server selects it
Create a new index that will remove the Sort operation. Test to ensure that the new index is being used. Results: After this exercise, you should have created a better index that will remove the sort operation.
Task 1: Open SQL Server Profiler and configure and start a trace
Open SQL Server Profiler. Configure it use the following: a. b. c. d. e. Template: Tuning Save To File: should be selected and any file name provided for a file on the desktop Enable file rollover: Not selected Maximum File Size: 500MB Filter: DatabaseName LIKE MarketDev
Start the SQL Server Profiler Trace. Disable AutoScroll from the Window Menu.
Module 9
Lab Instructions: Designing and Implementing Stored Procedures
Contents:
Exercise 1: Create stored procedures Exercise 2: Create a parameterized stored procedure Challenge Exercise 3: Alter the execution context of stored procedures (Only if time permits) 5 6 7
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
You need to create a set of stored procedures to support a new reporting application. The procedures will be created within a new Reports schema.
Supporting Documentation
Stored Procedure Input Parameters: Output Parameters: Output Columns: Output Order: Notes: Reports.GetProductColors None None Color (from Marketing.Product) Color Colors should not be returned more than once in the output. NULL values should not be returned. Reports.GetProductsAndModels None None ProductID, ProductName, ProductNumber, SellStartDate, SellEndDate and Color (from Marketing.Product), ProductModelID (from Marketing.ProductModel), EnglishDescription, FrenchDescription, ChineseDescription. ProductID, ProductModelID For descriptions, return the Description column from the Marketing.ProductDescription table for the appropriate language. The
Stored Procedure
Reports.GetProductColors LanguageID for English is 'en', for French is 'fr' and for Chinese is 'zh-cht'. If no specific language description is available, return the invariant language description if it is present. The LanguageID for the invariant language is a blank string ''. Where neither the specific language or invariant language descriptions exist, return the ProductName instead.
Reports.GetProductsByColor @Color (same datatype as the Color column in the Marketing.Product table) None ProductID, ProductName, ListPrice (returned as a column named Price), Color, Size and SizeUnitMeasureCode (returned as a column named UnitOfMeasure) (from Marketing.Product) ProductName The procedure should return products that have no Color if the parameter is NULL. None None Color (from Marketing.Product) Color Colors should not be returned more than once in the output. NULL values should not be returned.
Challenge Exercise 3: Alter the execution context of stored procedures (Only if time permits)
Scenario
In this exercise, you will alter the stored procedures to use a different execution context. The main tasks for this exercise are as follows: 1. 2. 3. Alter the Reports.GetProductColors stored procedure to execute as OWNER. Alter the Reports.GetProductsAndModels stored procedure to execute as OWNER. Alter the Reports.GetProductsByColor stored procedure to execute as OWNER.
Module 10
Lab Instructions: Merging Data and Passing Tables
Contents:
Exercise 1: Create a Table Type Exercise 2: Use a Table Type Parameter Challenge Exercise 3: Use a Table Type with MERGE (Only if time permits) 4 5 6
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
In earlier versions of SQL Server, passing lists of values to stored procedures was a challenge. SQL Server 2008 introduced the table type and table-valued parameters. In this lab, you will create a replacement stored procedure Reports.GetProductsByColorList_Test that uses a table-valued parameter to replace an existing stored procedure Reports.GetProductsByColorList that was based on passing a comma-delimited list of values. If time permits, you will then create a new procedure that processes complete rows of data and performs updates using the MERGE statement.
Supporting Documentation
Procedure Required: Marketing.SalespersonMerge Requirements Input Parameters: Table of Salesperson details, including SalespersonID, FirstName, MiddleName, LastName, BadgeNumber, EmailAlias, SalesTerritoryID. The parameter should be named: SalespersonDetails None For each row, return one column called Action that contains INSERT or UPDATE and another column with the SalespersonID. The SalespersonID must be provided. If it matches an existing salesperson, that row should be updated. Only update columns that are provided. Any SalesTerritoryID that is provided must be valid as it is defined as a foreign key to the Marketing.SalesTerritory table.
Notes:
Challenge Exercise 3: Use a Table Type with MERGE (Only if time permits)
Scenario
In this exercise, you will create a new stored procedure that takes a table-valued parameter and uses the MERGE statement to update a table in the marketing system. The procedure should allow for the creation or update of salespeople held in the Marketing.Salesperson table. The main tasks for this exercise are as follows: 1. 2. 3. Create a new table type Create a replacement procedure Test the replacement procedure.
Module 11
Lab Instructions: Creating Highly Concurrent SQL Server 2008 R2 Applications
Contents:
Exercise 1: Detecting Deadlocks Challenge Exercise 2: Investigating Transaction Isolation Levels (Only if time permits) 4 5
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_11_PRJ\6232B_11_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
In this lab, you will perform basic investigation of a deadlock situation. You are trying to determine an appropriate transaction isolation level for a new application. If you have time, you will investigate the trade-off between concurrency and consistency.
Execute the code step by step, making sure to highlight and execute just the required code blocks in each script window, by following the step by step instructions
Results: After this exercise, you will have seen how transaction isolation levels work.
Module 12
Lab Instructions: Handling Errors in T-SQL Code
Contents:
Exercise 1: Replace @@ERROR based error handling with structured exception handling Challenge Exercise 2: Add deadlock retry logic to the stored procedure (Only if time permits) 5 4
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logoncheck box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_12_PRJ\6232B_12_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
In this lab, a company developer asks you for assistance with some code he is modifying. The code was written some time back and uses simple T-SQL error handling. He has heard that structured exception handling is more powerful and wishes to use it instead. If time permits, you will also design and implement changes to a stored procedure to provide for automated retry on deadlock errors.
Exercise 1: Replace @@ERROR based error handling with structured exception handling
Scenario
In this exercise, you need to modify his code to use structured exception handling. The main tasks for this exercise are as follows: 1. 2. 3. Review the existing code Rewrite the stored procedure to use structured exception handling Test that the procedure
Challenge Exercise 2: Add deadlock retry logic to the stored procedure (Only if time permits)
Scenario
In this exercise, the operations team have mentioned that the same stored procedure also seems to routinely fail with deadlock errors. To assist them, make further modifications to your new procedure to add automatic retry code for deadlock errors. The main tasks for this exercise are as follows: 1. 2. Modify the code to re-try on deadlock Test the stored procedure
Module 13
Lab Instructions: Designing and Implementing User-Defined Functions
Contents:
Exercise 1: Formatting Phone Numbers Exercise 2: Modifying an Existing Function Challenge Exercise 3: Resolve a Function-related Performance Issue (Only if time permits) 7 5 6
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_13_PRJ\6232B_13_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
The existing marketing application includes some functions. Your manager has requested your assistance in creating a new function for formatting phone numbers. She also needs you to modify an existing function to improve its usability. Finally, if you have time, she would also like you to explore a performance-related problem with another existing function.
Supporting Documentation
Function Specifications: Phone Number Function Name: FormatPhoneNumber (created in the dbo schema) Input Parameter: PhoneNumberToFormat nvarchar(16) Return Value: nvarchar(16) Rules to apply in formatting: Any phone number beginning with the international dialing code (ie: a + sign), should be left unformatted. Phone numbers that contain 10 digits should be formatted as: (XXX) XXX-XXXX Phone numbers that contain 8 digits should be formatted as: XXXX-XXXX Phone numbers that contain 7 digits should be formatted as: XXX-XXXX Phone numbers that contain 6 digits should be formatted as: XXX-XXX All other characters should be stripped out Phone numbers that have different numbers of digits should have only the digits returned ie: (9234) 2345-2342 should be returned as 923423452342.
Requirements: Comma-Delimited List Function You need to create another version of this function called dbo.IntegerListToTable that takes a commadelimited list of integers and returns a similar table. You need to design, implement and test the function. You can assume that all integers sent to the function will be eight digits or less in length. Problematic Query
SELECT dbo.JoinNames(FirstName,MiddleName,LastName) AS FullName
Task 4: Test the function with an alternate delimiter such as the pipe | character
Test the dbo.IntegerListToTable function and pass in an alternate delimiter such as the pipe | character. Results: After this exercise, you should have created a new IntegerListToTable function within a dbo schema.
Task 3: Use SET STATISTICS TIME ON to compare the performance of the new and old
queries
Turn SET STATISTICS TIME ON. Use the times returned to test how your new query compares with the original. Results: After this exercise, you should have created an alternate query for the poorly-performing query.
Module 14
Lab Instructions: Ensuring Data Integrity through Constraints
Contents:
Exercise 1: Constraint Design Challenge Exercise 2: Test the constraints (Only if time permits) 4 5
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_14_PRJ\6232B_14_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
A table named Marketing.Yield has recently been added to the Marketing system in the MarketDev database but has no constraints in place. In this lab, you will implement the required constraints to ensure data integrity and, if you have time, test that constraints work as specified.
Supporting Documentation
Table Marketing.Yield Note: Primary key should be a combination of ProspectID and LanguageID and should be a clustered primary key. Mandatory Field Required Required Required
Validation rule Must be a valid prospect Must be a valid language Default value should be zero if not supplied Must be a value between 0 and 9
RowID
uniqueidentifier
Required
LastUpdate
datetime2
Required
Notes
nvarchar(MAX)
Optional
Module 15
Lab Instructions: Responding to Data Manipulation via Triggers
Contents:
Exercise 1: Creating and Testing the Audit Trigger Challenge Exercise 2: Improve the Audit Trigger (Only if time permits) 4 5
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
Log on using the following credentials: I. II. User name: AdventureWorks\Administrator Password: Pa$$w0rd
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. In Connect to Server window, type Proseware in the Server name text box. In the Authentication drop-down list box, select Windows Authentication and click Connect. In the File menu, click Open, and click Project/Solution. In the Open Project window, open the project D:\6232B_Labs\6232B_15_PRJ\6232B_15_PRJ.ssmssln. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
You are required to audit any changes to data in a table that hold sensitive balance data. You have decided to implement this via DML triggers as the requirements in this case are not provided for directly by the SQL Server Audit mechanism.`
Supporting Documentation
The Marketing.CampaignAudit table is used to hold audit entries. When inserting rows into this table, the data required in each column is as shown in the following table: Column CampaignAuditID AuditTime ModifyingUser RemainingBalance Data Type int datetime2 sysname decimal(18,2) Value to Insert IDENTITY SYSDATETIME() ORIGINAL_LOGIN() RemainingBalance after update
Task 2: Design a trigger to meet the requirements as stated in the scenario for this
exercise
Design and create a trigger that meets the needs identified in Task 1.
Module 16
Lab Instructions: Implementing Managed Code in SQL Server 2008 R2
Contents:
Exercise 1: Assess Proposed CLR Code Exercise 2: Implement a CLR Assembly Challenge Exercise 3: Implement a CLR User-defined Aggregate and CLR User-defined Data Type (Only if time permits) 6 4 5
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. In Connect to Server window, type Proseware in the Server name text box. In the Authentication drop-down list box, select Windows Authentication and click Connect. In the File menu, click Open, and click Project/Solution. In the Open Project window, open the project D:\6232B_Labs\6232B_16_PRJ\6232B_16_PRJ.ssmssln. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
You are concerned that one of your company developers has decided to implement almost all of her logic in SQL CLR assemblies. You will determine if this is appropriate. Also in this lab, you will implement and test a supplied .NET assembly. You will also investigate all installed assemblies on the system.
Supporting Documentation
The following list details the proposed functionality being considered for managed code. Proposed SQLCLR Functionality Table-valued function that returns a list of files in a particular folder. Function that formats phone numbers as strings. Trigger that records balance movements with a value of more than 1000. Stored procedure that writes an XML file for a given XML parameter. Function that counts rows in a table. A new Customer data type.
Results: After this exercise, you should have created a list of which objects should and should not be implemented in managed code and the reasons for your decision.
4.
5.
Results: After this exercise, you should have three functions working as expected.
Challenge Exercise 3: Implement a CLR User-defined Aggregate and CLR User-defined Data Type (Only if time permits)
Scenario
The sample assembly also includes a user-defined aggregate and a user-defined data type. You will now catalog and test these objects. The main tasks for this exercise are as follows: 1. 2. Catalog and test the user-defined aggregate Catalog and test the user-defined data type
CREATE TABLE dbo.TestTable ( RecID int IDENTITY(1,1), TextValue zVarChar ); INSERT INTO dbo.TestTable VALUES('Some GO SELECT TextValue.ToString(), TextValue.CompressedLength(), TextValue.CompressionPercentage() FROM dbo.TestTable; GO SELECT AVG(TextValue.CompressionPercentage()) FROM dbo.TestTable; GO DROP TABLE dbo.TestTable; GO compressible data');
3.
Execute the following T-SQL statements to see how to call a method on the class itself, rather than on an instance of the class. (First, show how to call the method on an instance. Then, show how to call directly on the class so that you can see the difference).
value';
Results: After this exercise, you should have cataloged and tested both the user-defined aggregate and the user-defined data type.
Module 17
Lab Instructions: Storing XML Data in SQL Server 2008 R2
Contents:
Exercise 1: Appropriate Usage of XML Data Storage in SQL Server Exercise 2: Investigate the Storage of XML Data in Variables Exercise 3: Investigate the use of XML Schema Collections Challenge Exercise 4: Investigate the Creation of Database Columns Based on XML (Only if time permits) 7 4 5 6
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
Log on using the following credentials: I. II. User name: AdventureWorks\Administrator Password: Pa$$w0rd
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. In Connect to Server window, type Proseware in the Server name text box. In the Authentication drop-down list box, select Windows Authentication and click Connect. In the File menu, click Open, and click Project/Solution. In the Open Project window, open the project D:\6232B_Labs\6232B_17_PRJ\6232B_17_PRJ.ssmssln. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
A new developer in your organization has discovered that SQL Server can store XML directly. He is keen to use this mechanism extensively. In this lab, you will decide on appropriate usage of XML within the documented application. You also have an upcoming project that will require the use of XML data within SQL Server. No members of your current team have experience working with XML data in SQL Server. You need to learn how to process XML data within SQL Server and you have been provided with some sample queries to assist with this learning.
Task 1: Review and execute the queries, and review the results
Review the queries, execute the queries and determine how the output results relate to the queries. Do this one query at a time for scripts 17.1 to 17.9.
Results: After this exercise, you have seen how XML data is stored in variables.
Task 1: Review and execute the queries, and review the results
Review the queries, execute the queries and note the output. Do this one query at a time for scripts 17.10 and 17.11.
Results: After this exercise, you have seen how to create XML schema collections.
Challenge Exercise 4: Investigate the Creation of Database Columns Based on XML (Only if time permits)
Scenario
The final aspect of XML data storage in SQL Server that you will need to understand for your upcoming project is how XML data is stored in tables. You need to investigate how columns of XML data type are used. You have been provided with a set of sample queries to assist with this. In this exercise, you will review the effect of executing these queries. The main tasks for this exercise are as follows: 1. Review and execute the queries, and review the results
Task 1: Review and execute the queries, and review the results
Review the queries, execute the queries and note the results of the queries. Do this one query at a time for scripts 17.12 to 17.20.
Results: After this exercise, you have seen how to create database columns based on the XML data type.
Module 18
Lab Instructions: Querying XML Data in SQL Server
Contents:
Exercise 1: Learn to query SQL Server data as XML Exercise 2: Write a stored procedure returning XML Challenge Exercise 3: Write a stored procedure that updates using XML (Only if time permits) 7 5 6
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. In Connect to Server window, type Proseware in the Server name text box. In the Authentication drop-down list box, select Windows Authentication and click Connect. In the File menu, click Open, and click Project/Solution. In the Open Project window, open the project D:\6232B_Labs\6232B_18_PRJ\6232B_18_PRJ.ssmssln. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
In this lab, you will investigate several ways in which XML data can be used in SQL Server. You will query relational data and return it as XML and also process existing XML data using T-SQL. If you have time, your manager has an additional task for you. A new web service is being added to the marketing system. You need to create a stored procedure that will query data from a table and return it as an XML value.
Output Order:
Task 1: Review and execute the query and review the results
Review the query, execute the query and review the results for scripts 18.1 to 18.9 Results: After this exercise, you have executed queries that return SQL Server relational data as XML.
Results: After this exercise, you should have created and tested the required stored procedure that returns XML.
Challenge Exercise 3: Write a stored procedure that updates using XML (Only if time permits)
Scenario
In this exercise, the reassignment of salesperson territories is done by an external management system. When it completes reassignments, it sends an XML document containing the changes. You need to construct a stored procedure Marketing.UpdateSalesTerritoriesByXML that can process this XML and use it to update the SalesTerritoryID column in the Marketing.Salesperson table. The main tasks for this exercise are as follows: 1. 2. 3. Review the requirements Create the stored procedure Test the stored procedure and ensure the updates have been applied
Results: After this exercise, you should have created and tested the required stored procedure that updates XML.
Module 19
Lab Instructions: Working with SQL Server 2008 R2 Spatial Data
Contents:
Exercise 1: Familiarity With Geometry Data Type Exercise 2: Adding Spatial Data to an Existing Table Challenge Exercise 3: Business Application of Spatial Data (Only if time permits) 6 4 5
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. In Connect to Server window, type Proseware in the Server name text box. In the Authentication drop-down list box, select Windows Authentication and click Connect. In the File menu, click Open, and click Project/Solution. In the Open Project window, open the project D:\6232B_Labs\6232B_19_PRJ\6232B_19_PRJ.ssmssln. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
Your organization has only recently begun to acquire spatial data within its databases. The new Marketing database was initially designed prior to the company beginning to implement spatial data. One of the developers has provided a table of the locations where prospects live. It is called Marketing.ProspectLocation. A second developer has added columns to it for Latitude and Longitude and geocoded the addresses. You will make some changes to the system to help support the need for spatial data.
Output Order
Results: After this exercise, you should have replaced the existing Longitude and Latitude columns with a new Location column.
Results: After this exercise, you should have created and tested the required stored procedure.
Module 20
Lab Instructions: Working with Full-Text Indexes and Queries
Contents:
Exercise 1: Implement a full-text index Exercise 2: Implement a stoplist Challenge Exercise 3: Create a stored procedure to implement a full-text search (Only if time permits) 6 4 5
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps: 1. 2. 3. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. Maximize the Hyper-V Manager window. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started: 4. Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User.
Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. In Connect to Server window, type Proseware in the Server name text box. In the Authentication drop-down list box, select Windows Authentication and click Connect. In the File menu, click Open, and click Project/Solution. In the Open Project window, open the project D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ.ssmssln. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
Users have been complaining about the limited querying ability provided in the marketing system. You are intending to use full-text indexing to address these complaints. You will implement a full-text index on the Marketing.ProductDescription table to improve this situation. You will implement a stoplist to avoid excessive unnecessary index size. If you have time, your manager would like you to help provide a more natural interface for your users. This will involve creating a new stored procedure.
Provide relevant results by using the FREETEXTTABLE function and limit your results to rows with LanguageID = 'en' (for English).
Results: After this exercise, you should have created and tested a full-text index.
Challenge Exercise 3: Create a stored procedure to implement a full-text search (Only if time permits)
Scenario
In this exercise, you want to provide a more natural interface for your users. In this exercise, you will create a stored procedure that implements a more advanced type of search. The main tasks for this exercise are as follows: 1. 2. Review the supporting documentation. Design, implement, and test the stored procedure.
Results: After this exercise, you should have created a new stored procedure and tested its behavior.
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
Module 1
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
Contents:
Exercise 1: Verify SQL Server Component Installation Exercise 2: Alter Service Accounts for New Instance Exercise 3: Enable Named Pipes Protocol for Both Instances Exercise 4: Create Aliases for AdventureWorks and Proseware Challenge Exercise 5: Ensure SQL Browser is Disabled and Configure a Fixed TCP/IP Port (Only if time permits) 2 4 4 5 6
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL1 is not started: Right-click 623XB-MIA-SQL1 and click Start. Right-click 623XB-MIA-SQL1 and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials: User name: AdventureWorks\Administrator Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
Note: The SQL Full-text Filter Daemon Launcher is present and it is part of the Database Engine.
Task 2: Note the services that are installed for the default instance and that Integration
Services is not installed on a per instance basis
1. 2. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services. In the right-hand pane, ensure that the following services are listed for the default instance: 3. SQL Server (MSSQLSERVER) SQL Full-text Filter Daemon Launcher (MSSQLSERVER) SQL Server Analysis Services (MSSQLSERVER) SQL Server Agent (MSSQLSERVER)
In the right-hand pane, note that SQL Server Integration Services 10.0 is not installed as a perinstance basis as there is no instance name shown.
Task 3: Ensure that all required services including SQL Server Agent are started and set
to autostart for both instances
1. Check that all the services for the MKTG instance have a Start Mode of Automatic. Ignore the SQL Full-text Filter Daemon Launcher service at this time. Note: The SQL Server Agent (MKTG) service is not set to autostart. 2. 3. 4. 5. 6. Right-click the SQL Server Agent (MKTG) service and click Properties. In the Log On tab, click Start and the SQL Server Agent service should start. In the Service tab, set the value for the Start Mode to Automatic, and then click OK. Check that all the services for the default instance have a Start Mode of Automatic. Ignore the SQL Full-text Filter Daemon Launcher service at this time. Check that the SQL Server Agent (MSSQLSERVER) service has Start Mode set to Automatic. Note: The SQL Server Agent (MSSQLSERVER) service is not set to autostart. 7. 8. Right-click the SQL Server Agent (MSSQLSERVER) service and click Properties. In the Log On tab, click Start and the SQL Server Agent service should start.
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
9.
In the Service tab, set the value for the Start Mode to Automatic, and then click OK.
10. The SQL Server Services need to be configured as the screenshot below:
Task 2: Change the service account for the MKTG SQL Server Agent
1. 2. 3. 4. 5. 6. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services. In the right-hand pane, right-click SQL Server Agent (MTKG), and select Properties. In the Account Name text box, type AdventureWorks\PWService. In the Password text box, type Pa$$w0rd. In the Confirm Password text box, type Pa$$w0rd and click OK. Right-click SQL Server Agent (MTKG) and select Start to restart the service.
Task 2: Enable the named pipes protocol for the MKTG instance
1. In the left-hand pane of the SQL Server Configuration Manager window, click Protocols for MKTG.
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
2. 3.
In the right-hand pane, right-click Named Pipes and select Enable. In the Warning window, click OK.
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
2. 3. 4. 5. 6.
Confirm that the Named Pipes protocol is Enabled. In the left-hand pane, right-click Aliases and select New Alias. In the Alias New window, in the Alias Name text box, type Proseware. In the Protocol drop-down list box, select Named Pipes. In the Server text box, type .\MKTG and click OK.
Task 5: Use SQL Server Management Studio to connect to both aliases to ensure they
work as expected
1. 2. 3. 4. 5. Click Start, click All Programs, click Microsoft SQL Server 2008 R2, and then click SQL Server Management Studio. In the Connect to Server window, ensure that Server Type is set to Database Engine. In the Server name text box, type Proseware. In the Authentication drop-down list, select Windows Authentication, and click Connect. In Object Explorer, under Proseware expand Databases. Note: The databases that are present include at least the following: System Databases, Database Snapshots, ReportServer$MKTG, and ReportServer$MKTGTempDB. 6. 7. 8. 9. In Object Explorer, click Connect, click Database Engine. In the Connect to Server window, ensure that Server Type is set to Database Engine. In the Server name text box, type AdventureWorks. In the Authentication drop-down list, select Windows Authentication, and click Connect.
10. In Object Explorer, under AdventureWorks expand Databases. Note: The databases that are present include at least the following: System Databases, Database Snapshots, AdventureWorks2008R2, and AdventureWorksDW2008R2. 11. Close SQL Server Management Studio. 12. Close SQL Server Configuration Manager.
Challenge Exercise 5: Ensure SQL Browser is Disabled and Configure a Fixed TCP/IP Port (Only if time permits)
Task 1: Configure the TCP port for the MKTG database engine instance to 51550
1. 2. 3. 4. 5. 6. In the Virtual Machine window, click Start. From the Start menu, click All Programs, click Microsoft SQL Server 2008 R2, click Configuration Tools, and then click SQL Server Configuration Manager. In the left-hand pane of the SQL Server Configuration Manager window, expand SQL Server Network Configuration and then click Protocols for MKTG. Right-click the TCP/IP protocol and select Properties. In the TCP/IP Properties window, click IP Addresses tab. Scroll to the bottom of the screen, under the IPAll section, clear the value for TCP Dynamic Ports.
Lab Answer Key: Introduction to SQL Server 2008 R2 and its Toolset
7. 8. 9.
For TCP Port, type 51550, and click OK. In the Warning window, click OK. In the left-hand pane, click SQL Server Services.
10. Right-click SQL Server (MKTG) and select Restart. 11. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services. 12. In the toolbar, click the Refresh icon and make sure the service starts.
Module 2
Lab Answer Key: Working with Data Types
Contents:
Exercise 1: Choosing Appropriate Data Types Exercise 2: Writing Queries With Data Type Conversions Challenge Exercise 3: Designing and Creating Alias Data Types (Only if time permits) 2 4 5
Table 1: PhoneCampaign Description Which campaign this relates to. The prospect that was contacted. When contact was first attempted with the prospect. Column Name and Data Type PhoneCampaignID INT NOT NULL ProspectID INT NOT NULL FirstAttemptedContact DATETIME NULL
Comments related to the contact that was made, if it ContactComments NVARCHAR(MAX) NULL was made. When contact was actually made with the prospect. Outcome of the contact: sale, later follow-up or no interest Value of any sale made (up to 2 decimal places) Table 2: Opportunity Description Name of the opportunity Which prospect this opportunity relates to Stage the sale is at: Lead, Qualification, Proposal Development, Contract Negotiations, Complete, Lost Date that the opportunity was raised Probability of success Rating: Cold, Warm, Hot Estimated closing date Estimated revenue Delivery address Table 3: SpecialOrder Description Which prospect this order is for External supplier of the item Description of the item Column Name and Data Type ProspectID INT NOT NULL SupplierID INT NOT NULL ItemDescription NVARCHAR(100) NOT NULL Column Name and Data Type OpportunityID INT NOT NULL ProspectID INT NOT NULL SalesStageCode CHAR(2) NOT NULL InitialContact DATETIME NULL ContactOutcomeCode CHAR(1) NULL
DateRaised DATETIME NOT NULL Likelihood TINYINT NOT NULL Rating CHAR(1) NOT NULL EstimatedClosingDate DATE NOT NULL EstimatedRevenue DECIMAL(10,2) NOT NULL DeliveryAddress NVARCHAR(MAX) NOT NULL
Description Quantity Required (some quantities are whole numbers, some are fractional with up to 3 decimal places) Date of order Promised delivery date Actual delivery date
OrderDate DATETIME NOT NULL PromisedDeliveryDate DATE NOT NULL ActualDeliveryDate DATE NULL
Special requirements (any comments related to the SpecialRequirements NVARCHAR(MAX) NULL special order) Quoted price per unit (up to 2 decimal places) QuotedPricePerUnit DECIMAL(10,2) NOT NULL
Task 2: Review the first query requirement and write a SELECT statement to meet the
requirement
1. 2. 3. 4. Review the supporting documentation for details for the first query requirement. In Object Explorer, expand the Databases under Proseware. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
SELECT ProductID, ProductName, CONVERT(varchar(8),SellEndDate,112) AS SellEndDate FROM Marketing.Product; GO
5. 6.
In the toolbar, click Execute. Ensure that the results from the query match the required output as shown in the supporting documentation.
Task 3: Review the second query requirement and write a SELECT statement to meet the
requirement
1. 2. 3. 4. Review the supporting documentation for details for the second query requirement. In Object Explorer, expand the Databases under Proseware. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
SELECT ProspectID,
5. 6.
In the toolbar, click Execute. Ensure that the results from the query match the required output as shown in the supporting documentation.
Challenge Exercise 3: Designing and Creating Alias Data Types (Only if time permits)
Task 1: Investigate the storage of phone numbers and email addresses
1. 2. In the Object Explorer, expand Databases, and expand MarketDev, and expand Tables. In each table, expand Columns, noting any columns that are holding details of Phone Numbers or Email Addresses. The following columns should be identified: Table Marketing.Prospect Marketing.Prospect Marketing.Prospect Phone Number Columns CellPhoneNumber HomePhoneNumber WorkPhoneNumber Definition NVARCHAR(20) NVARCHAR(25) VARCHAR(22)
4.
GO
4.
Module 3
Lab Answer Key: Designing and Implementing Tables
Contents:
Exercise 1: Improve the Design of Tables Exercise 2: Create a Schema Challenge Exercise 3: Create the Tables (Only if time permits) 2 5 5
Name CompetitorID
CompetitorName
The column name Name is too generic Unicode data type for flexibility Common to have multiple addresses Unicode data type for flexibility Removed underscore for consistency Chose appropriate data type Renamed for consistency Note: Suspect this should be a code or a number but would require more information from Business Analyst Unicode data type for flexibility
StreetAddress
DateEntered
Comments
NVARCHAR(max) NULL Unicode data type for flexibility NULL because there may be no comments
Table2A: City (Duplicated City details extracted from the original table called TVAdvertisements) Name CityID Data Type INT NOT NULL CityName NVARCHAR(25) NOT NULL Renamed original column Retained data type where no further information is available Design Rationale Added a surrogate key
Table2B: TVStation (Duplicated TV Station details extracted from the original table called TVAdvertisements) Name TVStationID Data Type INT NOT NULL NVARCHAR(15) NOT NULL Design Rationale Added a surrogate key
TVStationName
Renamed original column Retained data type where no further information is available City details extracted to a separate table
CityID
Name CostPerAdvertisement
TotalCostOfAllAdvertisements removed as it should be calculated NumberOfAdvertisements removed as it should be calculated Table2C: TVAdvertisement (Extracted repeating groups from the original table called TVAdvertisements) Name TVAdvertisementID Data Type INT NOT NULL INT NOT NULL DATETIME NOT NULL Design Rationale Added a surrogate key
TVStationID
ScreeningTime
Single data type to hold both values Name to reflect combination of values
Table3: CampaignResponse (Table name change to singular to match existing singular table names in the database and removed underscore for consistency) Name TVAdvertisementID Data Type INT NOT NULL DATETIME NOT NULL INT NOT NULL Design Rationale Added a surrogate key
ResponseReceived
ProspectID
Changed to a straightforward code using first letter An alternative would be to extract the response method as another lookup table Chose appropriate data type
ChargeFromReferrer
RevenueReceived
ResponseProfit should be removed as it should be calculated rather than stored in the table
2.
CREATE TABLE DirectMarketing.CampaignResponse ( CampaignResponseID INT NOT NULL PRIMARY KEY, ResponseReceived DATETIME NOT NULL, ProspectID INT NOT NULL, ResponseMethodCode CHAR(1) NOT NULL, ChargeFromReferrer DECIMAL(12,2) NOT NULL, RevenueReceived DECIMAL(12,2) NOT NULL ); GO
4.
Module 4
Lab Answer Key: Designing and Implementing Views
Contents:
Exercise 1: Design, Implement and Test the WebStock Views Exercise 2: Design and Implement the Contacts View Challenge Exercise 3: Modify the AvailableModels View (Only if time permits) 2 4 4
4.
3.
3.
4.
3.
3.
ALTER VIEW WebStock.AvailableModels AS SELECT p.ProductID, p.ProductName, pm.ProductModelID, pm.ProductModel, COALESCE(ed.Description,id.Description) AS CatalogDescription FROM Marketing.Product AS p INNER JOIN Marketing.ProductModel AS pm ON p.ProductModelID = pm.ProductModelID LEFT OUTER JOIN Marketing.ProductDescription AS ed ON pm.ProductModelID = ed.ProductModelID AND ed.LanguageID = 'en' LEFT OUTER JOIN Marketing.ProductDescription as id ON pm.ProductModelID = id.ProductModelID AND id.LanguageID = '' WHERE p.SellEndDate IS NULL AND p.SellStartDate IS NOT NULL; GO
3.
3. 4.
Module 5
Lab Answer Key: Planning for SQL Server 2008 R2 Indexing
Contents:
Exercise 1: Explore existing index statistics 2 Challenge Exercise 2: Design column orders for indexes (Only if time permits) 5
4.
5. 6. 7.
ii. Password: Pa$$w0rd From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.
8. 9. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_05_PRJ\6232B_05_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
4.
3.
3.
3.
Question
Answer
How many rows were sampled? How many steps were created? What was the average key length? How many Black products are there?
504 10 5.178571 93
3.
3.
4.
5. 6.
Highlight only Query 1 and click Execute. Calculate the selectivity of the query. Note: A sample result would be 2013 / 19955 or approximately 10.1%
7.
8. 9.
Highlight only Query 2 and click Execute. Calculate the selectivity of the query. Note: A sample result would be 48 / 19955 or approximately 0.2%
11. Highlight only Query 3 and click Execute. 12. Calculate the selectivity of the query. Note: A sample result would be 1 / 19955 or approximately 0.0%
Challenge Exercise 2: Design column orders for indexes (Only if time permits)
Task 1: Design an index
1. Review the supporting documentation for Query 1, the columns and column order is detailed in the table below: Columns ProspectID Column Order 1
Column Order 1 2
Rationale: Selecting only a single FirstName. Adding LastName to the index will supply the correct output order
Rationale: Selecting a range of FirstNames could have varying selectivity. In this case, the selectivity of the FirstName column is sufficient to warrant the index on the FirstName. Note that if the constant was an A rather than an S, the index would be better defined as LastName, FirstName instead
Rationale: Grouping by LanguageID. Note that in this case an alternate output order would not change the recommendation
Module 6
Lab Answer Key: Implementing Table Structures in SQL Server 2008 R2
Contents:
Exercise 1: Creating Tables as Heaps Exercise 2: Creating Tables with Clustered Indexes Challenge Exercise 3: Comparing the Performance of Clustered Indexes vs. Heaps (Only if time permits) 2 3 4
4.
5. 6. 7.
ii. Password: Pa$$w0rd From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.
8. 9. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
4.
4.
Challenge Exercise 3: Comparing the Performance of Clustered Indexes vs. Heaps (Only if time permits)
Task 1: Review the Table Design
1. Review the supporting documentation for Table 5.
4.
4.
ApplicantName nvarchar(150), EmailAddress nvarchar(100), ReferenceID uniqueidentifier, Comments nvarchar(500) ); GO CREATE CLUSTERED INDEX IX_EmailAddress ON Relationship.Table_EmailAddress (EmailAddress); GO
4.
4.
Note: this may take approximately five minutes to complete, depending on available hardware resources. You can check where it is up to by periodically switching to the Messages tab. A message is printed as each of the four sections is completed. While the script is running, review the contents of the script and estimate the proportion of time difference you expect to see in the results.
Note: Results will vary substantially depending upon the hardware the Virtual Machine is running on. Sample results are shown below. HeapTime 23 seconds ApplicationIDTime 21 seconds EmailAddressTime 91 seconds ReferenceIDTime 134 seconds
Module 7
Lab Answer Key: Reading SQL Server 2008 R2 Execution Plans
Contents:
Exercise 1: Actual vs. Estimated Plans Exercise 2: Identify Common Plan Elements Challenge Exercise 3: Query Cost Comparison (Only if time permits) 2 5 8
3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:
4.
5. 6. 7.
In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears. In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials: i. User name: AdventureWorks\Administrator
ii. Password: Pa$$w0rd From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.
8. 9. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
2.
USE AdventureWorks2008R2; GO
3.
2.
From the Query menu, select Display Estimated Execution Plan. Note: A Table Scan operator was used.
Task 3: View the estimated execution plan for script 7.2 using SHOWPLAN_XML
1. Highlight the following section of the script
SET SHOWPLAN_XML ON; GO SELECT * FROM dbo.DatabaseLog; GO SET SHOWPLAN_XML OFF; GO
2. 3. 4. 5.
In the toolbar, click Execute. In the Results pane, click on the XML that is returned to view the execution plan. In the Results pane, right-click in the whitespace in the plan, click Show Execution Plan XML. In the ExecutionPlanX.sqlplan tab, review the XML. Note: The XML is complex and it includes a large amount of detail that is not immediately obvious from the graphical plan.
6.
Close the XML window and the execution plan window. If prompted to save changes, do not save the changes.
3. 4.
Note: The plan is identical to the estimated plan from the previous task.
2.
From the Query menu, select Display Estimated Execution Plan. Note: An Estimated Execution Plan cannot be created. Note the reason (invalid object name) for the inability to create a plan in the messages tab.
2. 3.
In the toolbar, click Execute. Review the Execution Plan that has been returned. Note: The returned plan shows the INSERT and SELECT statements but not the CREATE and DROP statements.
Task 7: Review the execution plans currently cached in memory using script 7.5
1. Highlight the following section of the script
SELECT cp.objtype AS PlanType, OBJECT_NAME(st.objectid,st.dbid) AS ObjectName, cp.refcounts AS ReferenceCounts, cp.usecounts AS UseCounts, st.text AS SQLBatch, qp.query_plan AS QueryPlan FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st; GO
2.
3.
Review the results being returned. Note: The results returned will vary from system to system. Browse through the rows in the Results tab to gain an understanding of the types of plans currently in memory.
2.
3. 4.
In the toolbar, click Execute. From the Query menu click Include Actual Execution Plan.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Note: The table has a clustered index and the entire table is being read.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Note: The table has a clustered index and a specific clustering key is being used to seek.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Note: The table has a clustered index and the entire table is being read. The rows are then sorted by Shelf.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Note: The table is structured as a heap. The table has a nonclustered index on DatabaseLogID that is being used to locate the row required. Because the entire row is then required, a lookup is being made into the heap.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Note: The table has a clustered index. There is a nonclustered index that is sufficiently selective to be useful in locating entries for the given StateProvinceID. After the rows are located by that index, lookups to the clustered index need to be performed because not all columns that are required for the query are contained within the nonclustered index.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Compare this plan to the one returned in script 7.10.
4.
The reason why the plans are different can be attributed to Note: SQL Server has chosen to scan an entire index as it covers the query. The rows with the correct StateProvinceID are being selected from that index. Note the Missing Index hint that appears.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Note: SQL Server has decided to read an entire index that contains the City column rather than reading the entire table. As the index is not in City order, it then needs to execute a hash match aggregate operation to calculate the required aggregate.
2. 3. 4.
In the toolbar, click Execute. Explain the results being returned. Compare this plan to the one returned in script 7.12. The reason why the plans are different can be attributed to Note: There is a nonclustered index that is in StateProvinceID order. SQL Server has chosen to scan that index. As it is already in StateProvinceID order, a stream aggregate operation was able to be performed.
Task 10: Explain the actual execution plan from script 7.14
1. Highlight script 7.14 as shown in the code below
SELECT City, COUNT(City) AS CityCount FROM Person.Address GROUP BY City HAVING COUNT(1) > 5; GO
2. 3.
In the toolbar, click Execute. Note the difference in this plan from the plan for script 7.12.
Note: This query is identical to the one in script 7.12 with the addition of the HAVING clause. That clause has caused SQL Server to add a filter operation.
2.
3. 4.
In the toolbar, click Execute. From the Query menu click Include Actual Execution Plan.
2. 3.
In the toolbar, click Execute. Explain the results being returned. Note: Even though the two queries are structured quite differently, they are requesting exactly the same results in the same order. It is then logical that SQL Server executes the same plan for both queries.
Module 8
Lab Answer Key: Improving Performance through Nonclustered Indexes
Contents:
Exercise 1: Nonclustered index usage review Exercise 2: Improving nonclustered index designs Exercise 3: SQL Server Profiler and Database Engine Tuning Advisor Challenge Exercise 4: Nonclustered index design (Only if time permits) 2 3 4 6
4.
5. 6. 7.
ii. Password: Pa$$w0rd From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.
8. 9. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_08_PRJ\6232B_08_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
2.
3.
4.
3.
Task 3: Test the design and explain why the index was not used
1. 2. 3. Right-click the MarketDev database and click New Query. From the Query menu, click Include Actual Execution Plan. Type the query below in the query pane:
DECLARE @StartTime datetime2 = '2010-08-30 16:27'; SELECT TOP(5000) wl.SessionID, wl.ServerID, wl.UserName FROM Marketing.WebLog AS wl WHERE wl.SessionStart >= @StartTime ORDER BY wl.SessionStart, wl.ServerID; GO
4.
In the toolbar, click Execute. Note: The structure of the index does not support efficient selection of rows or ordering of results.
2.
Task 3: Design a more appropriate index by following the Missing Index suggestion
1. 2. 3. Right-click the MarketDev database and click New Query. From the Query menu, click Include Actual Execution Plan. Type the query below in the query pane:
SELECT PostalCode, Country FROM Marketing.PostalCode WHERE StateCode = 'KY' ORDER BY StateCode, PostalCode; GO
4. 5. 6.
In the toolbar, click Execute. In the Execution Plan tab, note the missing index suggestion in green. Right-click in whitespace in the middle of the graphical execution plan and choose Missing Index Details.
Note: Review the suggested index design. 7. 8. Close the Missing Index Details query window. Type the query below in the previous query pane:
CREATE NONCLUSTERED INDEX IX_PostalCode_Perf_20100830_A ON Marketing.PostalCode (StateCode) INCLUDE (Country,PostalCode); GO
9.
10. Highlight the previous query as shown below in the query pane:
SELECT PostalCode, Country FROM Marketing.PostalCode WHERE StateCode = 'KY' ORDER BY StateCode, PostalCode; GO
11. In the toolbar, click Execute. 12. In the Execution Plan tab, note that the missing index suggestion has now disappeared. Note: The query is now utilizing the new index. 13. Leave the query pane open for the next task.
Task 4: Create a better index that removes the sort operation. If you create another
index, confirm that SQL Server selects it
1. Type the query below in the query pane from the previous task:
CREATE NONCLUSTERED INDEX IX_PostalCode_Perf_20100830_B ON Marketing.PostalCode (StateCode, PostalCode) INCLUDE (Country); GO
2. 3.
Highlight the above query, click Execute. Highlight the previous query as shown below in the query pane:
SELECT PostalCode, Country FROM Marketing.PostalCode WHERE StateCode = 'KY' ORDER BY StateCode, PostalCode; GO
4. 5.
In the toolbar, click Execute. Click on the Execution Plan tab. Note: The sort operation is now unnecessary and the new index is now utilized.
10. Click Events Selection tab, and click Column Filters. 11. In the Edit Filter pane, click the DatabaseName column header. 12. In the DatabaseName pane, expand the Like node, type MarketDev, and click OK. 13. In the Trace Properties window, click Run. 14. In the Window menu, ensure that AutoScroll is not selected.
6.
7. 8. 9.
In the Database for workload analysis dropdown, select MarketDev. In the Select databases and tables to tune list, check the MarketDev database. Click the Tuning Options tab and click Advanced Options.
10. In the Advanced Tuning Options window, check the Define max space for recommendations (MB) checkbox and enter 500 for the size and click OK. 11. From the toolbar, click the Start Analysis. Note: Observe the tuning progress and when the analysis is complete, note the recommendations. The exact recommendations you see will depend upon how long you ran the query, etc. but it is likely you will see a recommendation for two new indexes and a substantial estimated performance improvement. 12. On the Recommendations tab, note the Estimated improvement. 13. Scroll the Index Recommendations output to the right and note the hyperlinks to sample code. 14. Click each of the recommendations in the Definition column turn and note the suggested index structures. 15. Close DTA. 16. Close SQL Server Profiler.
Module 9
Lab Answer Key: Designing and Implementing Stored Procedures
Contents:
Exercise 1: Create stored procedures Exercise 2: Create a parameterized stored procedure Challenge Exercise 3: Alter the execution context of stored procedures (Only if time permits) 2 4 4
4.
5. 6. 7.
ii. Password: Pa$$w0rd From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio.
8. 9. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_09_PRJ\6232B_09_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
2.
3.
In the toolbar, click Execute. Note: Ensure that approximately 9 colors are returned and that no NULL row is returned.
3.
In the toolbar, click Execute. Note: Ensure that approximately 504 rows are returned. Check that appropriate language descriptions appear. ProductID 1 should have the same description for all three languages. ProductID 776 should have different descriptions for each language.
3.
In the toolbar, click Execute. Note: Ensure that approximately 26 rows are returned for blue products. Ensure that approximately 248 rows are returned for products with no color.
Challenge Exercise 3: Alter the execution context of stored procedures (Only if time permits)
Task 1: Alter the Reports.GetProductColors stored procedure to execute as OWNER
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
ALTER PROCEDURE Reports.GetProductColors WITH EXECUTE AS OWNER AS SELECT DISTINCT p.Color FROM Marketing.Product AS p WHERE p.Color IS NOT NULL ORDER BY p.Color; GO EXEC Reports.GetProductColors; GO
3.
In the toolbar, click Execute. Check that the procedure still executes without error.
3.
In the toolbar, click Execute. Check that the procedure still executes without error.
2.
3.
In the toolbar, click Execute. Check that the procedure still executes without error.
Module 10
Lab Answer Key: Merging Data and Passing Tables
Contents:
Exercise 1: Create a Table Type Exercise 2: Use a Table Type Parameter Challenge Exercise 3: Use a Table Type with MERGE (Only if time permits) 2 3 4
3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:
Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window. 4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears. 5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials: i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd 8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_10_PRJ\6232B_10_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
2.
3.
3.
3.
3.
Challenge Exercise 3: Use a Table Type with MERGE (Only if time permits)
Task 1: Create a new table type
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
CREATE TYPE dbo.SalespersonList AS TABLE (SalespersonID int NOT NULL, FirstName nvarchar(50) NULL, MiddleName nvarchar(50) NULL, LastName nvarchar(50) NULL, BadgeNumber nvarchar(15) NULL, EmailAlias nvarchar(256) NULL, SalesTerritoryID int NULL); GO
3.
2. 3.
4.
3.
In the toolbar, click Execute. Note: The output should show UPDATE for SalesPersonID 276 and should show INSERT for SalesPersonID 601.
Lab Answer Key: Creating Highly Concurrent SQL Server 2008 R2 Applications
Module 11
Lab Answer Key: Creating Highly Concurrent SQL Server 2008 R2 Applications
Contents:
Exercise 1: Detecting Deadlocks 3
Lab Answer Key: Creating Highly Concurrent SQL Server 2008 R2 Applications
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials: i. ii. User name: AdventureWorks\Administrator Password: Pa$$w0rd
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_11_PRJ\6232B_11_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Answer Key: Creating Highly Concurrent SQL Server 2008 R2 Applications
4. 5.
Lab Answer Key: Creating Highly Concurrent SQL Server 2008 R2 Applications
Note: When you hover your mouse over a process, you will see a pop-up window displaying the TSQL statement that was executed. 7. Close SQL Server Profiler.
2. 3.
Module 12
Lab Answer Key: Handling Errors in T-SQL Code
Contents:
Exercise 1: Replace @@ERROR based error handling with structured exception handling Challenge Exercise 2: Add deadlock retry logic to the stored procedure (Only if time permits) 4 3
In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started: Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.
5. 6. 7.
In Virtual Machine Connection window, click on the Revert toolbar icon. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. In the Virtual Machine Connection window, if the user is not already logged on: On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:
8. 9.
i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window.
10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_12_PRJ\6232B_12_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
Exercise 1: Replace @@ERROR based error handling with structured exception handling
Task 1: Review the existing code
1. In Object Explorer, expand Proseware, expand Databases, expand MarketDev, expand Programmability, expand Stored Procedures, right-click Marketing.MoveCampaignBalance, and click Modify. Review the existing stored procedure.
2.
3. 4.
In the toolbar, click Execute. Leave the query window open for use in the next exercise.
3.
In the toolbar, click Execute. Note: You should see two messages each indicating that a single row has been updated.
4.
Leave the query window open for use in the next exercise.
Challenge Exercise 2: Add deadlock retry logic to the stored procedure (Only if time permits)
Task 1: Modify the code to re-try on deadlock
1. In SQL Server Management Studio, return to the query window with the Marketing.MoveCampaignBalance_Test stored procedure code. Modify the query as per the code shown below:
ALTER PROCEDURE Marketing.MoveCampaignBalance_Test ( @FromCampaignID int, @ToCampaignID int, @BalanceToMove decimal(18,2) ) AS BEGIN DECLARE @RetriesRemaining int = 5; SET XACT_ABORT ON; WHILE (@RetriesRemaining > 0) BEGIN BEGIN TRY BEGIN TRANSACTION UPDATE Marketing.CampaignBalance SET RemainingBalance -= @BalanceToMove WHERE CampaignID = @FromCampaignID; UPDATE Marketing.CampaignBalance SET RemainingBalance += @BalanceToMove WHERE CampaignID = @ToCampaignID; COMMIT TRANSACTION; SET @RetriesRemaining = 0; END TRY BEGIN CATCH IF (ERROR_NUMBER() = 1205) BEGIN SET @RetriesRemaining -=1; PRINT 'Warning: deadlock retry'; WAITFOR DELAY '00:00:05'; END ELSE BEGIN SET @RetriesRemaining = 0; -- exit the retry loop IF XACT_STATE() <> 0 ROLLBACK TRANSACTION; PRINT 'Unable to move balance'; RETURN 1; END; END CATCH; END; END; GO
2.
3.
2.
Note: You should see two messages each indicating that a single row has been updated.
Module 13
Lab Answer Key: Designing and Implementing User-Defined Functions
Contents:
Exercise 1: Formatting Phone Numbers Exercise 2: Modifying an Existing Function Challenge Exercise 3: Resolve a Function-related Performance Issue (Only if time permits) 5 3 4
3.
3.
Note: The output should resemble the following: +61 3 9485-2342 (415) 485-2342 (415) 485-2342 9485-2342 852-342
3.
3.
In the toolbar, click Execute. Note: The output should resemble the following:
Task 4: Test the function with an alternate delimiter such as the pipe | character
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
SELECT * FROM dbo.IntegerListToTable('234|354253|3242|2','|'); GO
3.
In the toolbar, click Execute. Note: The output should resemble the following:
ORDER BY FullName; SELECT FirstName + N' ' + CASE WHEN LEN(MiddleName) > 0 THEN MiddleName + N' ' ELSE N'' END + LastName AS FullName FROM Marketing.Prospect ORDER BY FullName; GO
3.
Task 3: Use SET STATISTICS TIME ON to compare the performance of the new and old
queries
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
SET STATISTICS TIME ON; GO SELECT dbo.JoinNames(FirstName,MiddleName,LastName) AS FullName FROM Marketing.Prospect ORDER BY FullName; GO SELECT FirstName + N' ' + CASE WHEN LEN(MiddleName) > 0 THEN MiddleName + N' ' ELSE N'' END + LastName AS FullName FROM Marketing.Prospect ORDER BY FullName; GO SET STATISTICS TIME OFF; GO
3.
Note: The execution time for the alternate query should be shorter than the time for the original query. The actual times will vary from computer to computer. The output should resemble the following:
Module 14
Lab Answer Key: Ensuring Data Integrity through Constraints
Contents:
Exercise 1: Constraint Design Challenge Exercise 2: Test the constraints (Only if time permits) 2 4
4.
5. 6. 7.
i. ii.
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_14_PRJ\6232B_14_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
2.
3.
3.
In the toolbar, click Execute. Note: This should execute without errors.
GO
Module 15
Lab Answer Key: Responding to Data Manipulation via Triggers
Contents:
Exercise 1: Creating and Testing the Audit Trigger Challenge Exercise 2: Improve the Audit Trigger (Only if time permits) 3 4
2.
3.
Task 2: Design a trigger to meet the requirements as stated in the scenario for this
exercise
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
CREATE TRIGGER Marketing.TR_CampaignBalance_Update ON Marketing.CampaignBalance AFTER UPDATE AS BEGIN SET NOCOUNT ON; INSERT Marketing.CampaignAudit (AuditTime, ModifyingUser, RemainingBalance) SELECT SYSDATETIME(), ORIGINAL_LOGIN(), inserted.RemainingBalance FROM deleted INNER JOIN inserted ON deleted.CampaignID = inserted.CampaignID WHERE deleted.RemainingBalance > 10000 OR inserted.RemainingBalance > 10000; END; GO
3.
3.
In the toolbar, click Execute. Note: The output should be similar to the following:
Note: The dates and times will depend upon when you execute the code.
2. 3. 4.
5.
3.
3.
In the toolbar, click Execute. Note: The output should be similar to the following:
Note: The dates and times will depend upon when you execute the code.
Module 16
Lab Answer Key: Implementing Managed Code in SQL Server 2008 R2
Contents:
Exercise 1: Assess Proposed CLR Code Exercise 2: Implement a CLR Assembly Challenge Exercise 3: Implement a CLR User-defined Aggregate and CLR User-defined Data Type (Only if time permits) 5 2 3
Table-valued function that returns a list of files Yes, good use of external access. in a particular folder. Function that formats phone numbers as strings. Trigger that records balance movements with a value of more than 1000. Stored procedure that writes an XML file for a given XML parameter. Function that counts rows in a table. A new Customer data type. Yes, good use of string handling.
No, only involves data access. No, not an object oriented database.
2.
3.
2.
3. 4.
In the toolbar, click Execute. Type the query below in the query pane:
SELECT * FROM sys.assemblies; SELECT * FROM sys.assembly_files; GO
5. 6.
Highlight the query above and in the toolbar click Execute. Type the query below in the query pane:
CREATE FUNCTION dbo.IsValidEmailAddress(@email NVARCHAR(4000)) RETURNS BIT AS EXTERNAL NAME SQLCLRDemo.[SQLCLRDemo.CLRDemoClass].IsValidEmailAddress; GO
7. 8.
Highlight the query above and in the toolbar click Execute. Type the query below in the query pane:
CREATE FUNCTION dbo.FormatAustralianPhoneNumber(@PhoneNumber NVARCHAR(4000)) RETURNS NVARCHAR(4000) AS EXTERNAL NAME SQLCLRDemo.[SQLCLRDemo.CLRDemoClass].FormatAustralianPhoneNumber; GO
9.
11. Highlight the query above and in the toolbar click Execute.
3.
Challenge Exercise 3: Implement a CLR User-defined Aggregate and CLR Userdefined Data Type (Only if time permits)
Task 1: Catalog and test the user-defined aggregate
1. 2. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
CREATE AGGREGATE dbo.AggString(@s nvarchar(4000)) RETURNS nvarchar(4000) EXTERNAL NAME SQLCLRDemo.[SQLCLRDemo.AggString]; GO SELECT dbo.AggString(DISTINCT ProductNumber) FROM Marketing.Product WHERE Color = 'Black'; GO
3.
3. 4. 5.
In the toolbar, click Execute. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
CREATE TABLE dbo.TestTable ( RecID int IDENTITY(1,1), TextValue zVarchar ); GO
6. 7. 8.
In the toolbar, click Execute. Right-click the MarketDev database and click New Query. Type the query below in the query pane:
INSERT INTO dbo.TestTable VALUES('Some GO SELECT TextValue.ToString(), TextValue.CompressedLength(), TextValue.CompressionPercentage() FROM dbo.TestTable; GO compressible data');
9.
10. Right-click the MarketDev database and click New Query. 11. Type the query below in the query pane:
DECLARE @TestString zVarChar; SET @TestString = 'Some compressible PRINT @TestString.CompressedValue(); GO PRINT zVarChar::Compress( 'Some compressible GO value');
value';
Module 17
Lab Answer Key: Storing XML Data in SQL Server 2008 R2
Contents:
Exercise 1: Appropriate Usage of XML Data Storage in SQL Server Exercise 2: Investigate the Storage of XML Data in Variables Exercise 3: Investigate the use of XML Schema Collections Challenge Exercise 4: Investigate the Creation of Database Columns Based on XML (Only if time permits) 7 3 3 5
4.
5. 6. 7.
i. ii.
8. 9.
From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. If the Server Manager window appears, check the Do not show me this console at logon check box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project D:\6232B_Labs\6232B_17_PRJ\6232B_17_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.
No Perhaps
Yes
USE tempdb; GO
3.
Highlight and execute scripts 17.1 to 17.9 separately, comparing the results of each script with the script comment.
-- Script 17.1 Create a table with an xml column CREATE TABLE #Invoices ( InvoiceID int, SalesDate datetime, CustomerID int, ItemList xml); GO -- Script 17.2 Use implicit casting to assign an xml variable DECLARE @itemString nvarchar(2000); SET @itemString = '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'; DECLARE @itemDoc xml; SET @itemDoc = @itemString;
INSERT INTO #Invoices VALUES (1, GetDate(), 2, @itemDoc); SELECT * FROM #Invoices; GO -- Script 17.3 Use implicit casting to assign a string constant INSERT INTO #Invoices VALUES (1, GetDate(), 2, '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'); SELECT * FROM #Invoices; GO -- Script 17.4 Explicitly cast string to xml DECLARE @varToCast nvarchar(2000); SET @varToCast = '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'; DECLARE @castedDoc xml; SET @castedDoc = CAST(@varToCast AS xml); INSERT INTO #Invoices VALUES(1, GetDate(), 2, @castedDoc); SELECT * FROM #Invoices; GO -- Script 17.5 Explicitly convert string to xml DECLARE @varToConvert nvarchar(2000); SET @varToConvert = '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'; DECLARE @convertedDoc xml; SET @convertedDoc = CONVERT(xml, @varToConvert); INSERT INTO #Invoices VALUES(1, GetDate(), 2, @convertedDoc); SELECT * FROM #Invoices; GO -- Script 17.6 Well-formed document. This will succeed INSERT INTO #Invoices VALUES (1, GetDate(), 2, '<?xml version="1.0" ?> <Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/> </Items>'); SELECT * FROM #Invoices; GO -- Script 17.7 Well-formed fragment. This will succeed INSERT INTO #Invoices VALUES (1, GetDate(), 2, '<Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/>');
SELECT * FROM #Invoices; GO -- Script 17.8 Not well-formed. This will fail INSERT INTO #Invoices VALUES (1, GetDate(), 2, '<Items> <Item ProductID="2" Quantity="3"/> <Item ProductID="4" Quantity="1"/>'); SELECT * FROM #Invoices; GO -- Script 17.9 Clean up the temporary table DROP TABLE #Invoices; GO
4.
Review the results from each script. Query Number 17.1 17.2 Query Title Create a table with an xml column. Use implicit casting to assign an xml variable. Use implicit casting to assign a string constant. Explicitly cast string to xml. Explicitly convert string to xml. Well-formed document. This will succeed. Output Command completed successfully. One row is inserted.
17.3
17.7 17.8
Well-formed fragment. This will succeed. One row is inserted. Not well-formed. This will fail. Command will fail due to incorrect XML format. Command completed successfully.
17.9
USE tempdb; GO
3.
Highlight and execute scripts 17.10 to 17.11 separately, comparing the results of each script with the script comment.
-- Script 17.10 Create an xml schema collection for resumes CREATE XML SCHEMA COLLECTION ResumeSchemaCollection AS N'<?xml version="1.0" ?> <xsd:schema targetNamespace="http://schemas.adventure-works.com/EmployeeResume" xmlns="http://schemas.adventure-works.com/EmployeeResume" elementFormDefault="qualified" attributeFormDefault="unqualified" xmlns:xsd="http://www.w3.org/2001/XMLSchema" > <xsd:element name="resume"> <xsd:complexType> <xsd:sequence> <xsd:element name="name" type="xsd:string" minOccurs="1" maxOccurs="1"/> <xsd:element name="employmentHistory"> <xsd:complexType> <xsd:sequence minOccurs="1" maxOccurs="unbounded"> <xsd:element name="employer"> <xsd:complexType> <xsd:simpleContent> <xsd:extension base="xsd:string"> <xsd:attribute name="endDate" use="optional"/> </xsd:extension> </xsd:simpleContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:complexType> </xsd:element> </xsd:schema>'; GO -- Script 17.11 Retrieve information about the components in the schema collection -Note that schemas are stored as components, not as the original -schema text SELECT cp.* FROM sys.xml_schema_components AS cp JOIN sys.xml_schema_collections AS c ON cp.xml_collection_id = c.xml_collection_id WHERE c.name = 'ResumeSchemaCollection'; GO
4.
Review the results from each script. Query Number 17.10 Query Title Create an xml schema collection for resumes. Output Schema collection is created.
17.11
Retrieve information about Ten rows showing how the individual components of the XML schema collection are stored. Note the the components in the schema collection values in the kind_desc column.
Challenge Exercise 4: Investigate the Creation of Database Columns Based on XML (Only if time permits)
Task 1: Review and execute the queries, and review the results
1. 2. Double-click the script 81 Lab Exercise 4.sql, in Solution Explorer. Highlight and execute the first command block as shown:
USE tempdb; GO
3.
Highlight and execute scripts 17.12 to 17.20 separately, comparing the results of each script with the script comment.
-- Script 17.12 Create a table with a typed xml column for documents CREATE TABLE #EmployeeResume ( EmployeeID int, Resume xml (ResumeSchemaCollection)); GO -- Script 17.13 Insert valid XML INSERT INTO #EmployeeResume VALUES (1, '<?xml version="1.0" ?> <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>'); SELECT * FROM #EmployeeResume; GO -- Script 17.14 Try to insert invalid XML (this will fail) INSERT INTO #EmployeeResume VALUES (1, '<?xml version="1.0" ?> <resume xmlns = "http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> </resume>'); GO -- Script 17.15 Use CONTENT keyword CREATE TABLE #EmployeeResumeContent ( EmployeeID int, Resume xml (CONTENT ResumeSchemaCollection)); GO -- Script 17.16 Insert a single document into a CONTENT column INSERT INTO #EmployeeResumeContent VALUES (1, '<?xml version="1.0" ?> <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>');
SELECT * FROM #EmployeeResumeContent; GO -- Script 17.17 Insert multiple valid elements into a CONTENT column INSERT INTO #EmployeeResumeContent VALUES (1, ' <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> </employmentHistory> </resume> <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>'); SELECT * FROM #EmployeeResumeContent; GO -- Script 17.18 Use DOCUMENT keyword CREATE TABLE #EmployeeResumeDocument ( EmployeeID int, Resume xml (DOCUMENT ResumeSchemaCollection)); GO -- Script 17.19 Insert a single document into a DOCUMENT column INSERT INTO #EmployeeResumeDocument VALUES (1, '<?xml version="1.0" ?> <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>'); SELECT * FROM #EmployeeResumeDocument; GO -- Script 17.20 Insert multiple valid elements into a DOCUMENT column. This will fail. INSERT INTO #EmployeeResumeDocument VALUES (1, ' <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> </employmentHistory> </resume> <resume xmlns="http://schemas.adventure-works.com/EmployeeResume"> <name>Guy Gilbert</name> <employmentHistory> <employer endDate="2000-07-07">Northwind Traders</employer> <employer>Adventure Works</employer> </employmentHistory> </resume>');
4.
Review the results from each script. Query Number 17.12 Query Title Output
Create a table with a typed xml column Command completed successfully. for documents. Insert valid XML. Try to insert invalid XML (this will fail). One row is inserted. No rows are inserted. Even though wellformed XML was supplied, it did not meet the required schema. Command completed successfully. One row is inserted.
17.13 17.14
17.15 17.16
Use CONTENT keyword. Insert a single document into a CONTENT column. Insert multiple valid elements into a CONTENT column.
17.17
One row is inserted. Note the row is inserted, even though no root element is present. Command completed successfully. One row is inserted.
17.18 17.19
Use DOCUMENT keyword. Insert a single document into a DOCUMENT column. Insert multiple valid elements into a DOCUMENT column. This will fail.
17.20
Module 18
Lab Answer Key: Querying XML Data in SQL Server
Contents:
Exercise 1: Learn to query SQL Server data as XML Exercise 2: Write a stored procedure returning XML Challenge Exercise 3: Write a stored procedure that updates using XML (Only if time permits) 5 2 4
-- Script 18.1 FOR XML AUTO Use MarketDev GO SELECT ProductID, ProductName, ListPrice FROM Marketing.Product FOR XML AUTO; GO -- Script 18.2 ELEMENTS with RAW mode SELECT ProductID, ProductName, ListPrice FROM Marketing.Product FOR XML RAW, ELEMENTS; GO -- Script 18.3 NULL columns with ELEMENTS SELECT ProductID, ProductName, Color FROM Marketing.Product FOR XML AUTO, ELEMENTS XSINIL; GO -- Script 18.4 Note the effect of the column alias compared to 18.3 SELECT ProductID, ProductName, Color FROM Marketing.Product AS Product FOR XML AUTO, ELEMENTS XSINIL; GO -- Script 18.5 Inline XSD schema SELECT ProductID, ProductName, ListPrice FROM Marketing.Product AS Product FOR XML AUTO, XMLSCHEMA; GO -- Script 18.6 Nested XML with TYPE SELECT ProductID, ProductName, ListPrice, (SELECT Description.ProductModelID, Description.Description FROM Marketing.ProductDescription AS Description WHERE Description.ProductModelID = Product.ProductModelID FOR XML AUTO, ELEMENTS, TYPE) AS Description FROM Marketing.Product AS Product; GO -- Script 18.7 PATH mode SELECT ProductID AS "@ProductID", ProductName AS "*", Size AS "Description/@Size", Color AS "Description/text()" FROM Marketing.Product AS Product FOR XML PATH; GO -- Script 18.8 ROOT directive SELECT ProductID, ProductName, ListPrice FROM Marketing.Product AS Product FOR XML AUTO, ROOT('AvailableItems'); GO -- Script 18.9 Named element in RAW modes SELECT ProductID, ProductName, ListPrice FROM Marketing.Product AS Product FOR XML RAW('AvailableItem');
GO
Output One row per product. Note the element name is based on the table name. Note the element centric output and the element name is row. Products without color show xsi:nil=true. Other products show the color.
18.2
18.3
18.4
Note the effect of the Note the element name is now Product, based on the alias column alias name of the table. compared to 18.3. Inline XSD schema. Nested XML with TYPE. PATH Mode. Note the inclusion of an XSD schema. Note that rows with a value in the Description column show that value as XML. Note how the output can be constructed with a PATH query. In the output locate each of the elements in the SELECT clause. Note the AvailableItems root node. Note the AvailableItem ElementName.
18.5 18.6
18.7
18.8 18.9
INNER JOIN Marketing.ProductModel AS pm ON p.ProductModelID = pm.ProductModelID WHERE p.SellStartDate IS NOT NULL AND p.SellEndDate IS NULL ORDER BY p.SellStartDate, p.ProductName FOR XML RAW('AvailableModel'), ROOT('AvailableModels'); END; GO
3.
3.
Challenge Exercise 3: Write a stored procedure that updates using XML (Only if time permits)
Task 1: Review the requirements
1. Review the supplied stored procedure specification in the supporting documentation for Marketing.UpdateSalesTerritoriesByXML.
3.
2.
3.
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
Module 19
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
Contents:
Exercise 1: Familiarity With Geometry Data Type Exercise 2: Adding Spatial Data to an Existing Table Challenge Exercise 3: Business Application of Spatial Data (Only if time permits) 11 2 10
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
-- Script 19.1 Draw a square USE tempdb; GO DECLARE @Shape GEOMETRY; SET @Shape = GEOMETRY::STGeomFromText('POLYGON ((10 10, 10 40, 40 40, 40 10, 10 10))',0); SELECT @Shape AS Square; GO -- Script 19.2 Try an invalid value - note the 6522 error and the wrapped error message BEGIN TRY DECLARE @Shape GEOMETRY; SET @Shape = GEOMETRY::STPolyFromText('POLYGON((0 0,20 15,10 10,0 15,5 5))', 0); END TRY BEGIN CATCH SELECT ERROR_MESSAGE(); END CATCH; GO -- Script 19.3 Draw a more complex shape DECLARE @Shape GEOMETRY; SET @Shape = GEOMETRY::STGeomFromText('POLYGON ((10 10, 5 5,10 40, 40 40, 45 45,40 10, 10 10))',0); SELECT @Shape AS ColoredArea; GO -- Script 19.4 Multiple shapes DECLARE @Shape1 GEOMETRY, @Shape2 GEOMETRY; SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10, 5 5,10 40, 40 40, 45 45,40 10, 10 10))',0); SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((60 25, 55 5,60 40, 90 40, 95 45,90 10, 60 25))',0); SELECT @Shape1 AS Multishapes UNION ALL SELECT @Shape2; GO -- Script 19.5 Intersecting shapes DECLARE @Shape1 GEOMETRY, @Shape2 GEOMETRY; SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10, 5 5,10 40, 40 40, 45 45,40 10, 10 10))',0); SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((30 25, 25 5,30 40, 60 40, 65 45,60 20, 30 25))',0); SELECT @Shape1 AS Overlapping UNION ALL SELECT @Shape2; GO -- Script 19.6 Union of the two shapes DECLARE @Shape1 GEOMETRY, @Shape2 GEOMETRY; SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10, 5 5,10 40, 40 40, 45 45,40 10, 10 10))',0); SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((30 25, 25 5,30 40, 60 40, 65 45,60 20, 30 25))',0); SELECT @Shape1.STUnion(@Shape2) AS Unioned; GO -- Script 19.7 Intersection of shapes DECLARE @Shape1 GEOMETRY, @Shape2 GEOMETRY; SET @Shape1 = GEOMETRY::STGeomFromText('POLYGON ((10 10, 5 5,10 40, 40 40, 45 45,40 10, 10 10))',0);
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
SET @Shape2 = GEOMETRY::STGeomFromText('POLYGON ((30 25, 25 5,30 40, 60 40, 65 45,60 20, 30 25))',0); SELECT @Shape1 AS Intersected UNION ALL SELECT @Shape2 UNION ALL SELECT @Shape1.STIntersection(@Shape2); GO -- Script 19.8 Draw Australia DECLARE @Australia geometry; SET @Australia = geometry::STGeomFromText('MULTIPOLYGON (((146.91639709472656 43.704837799072266, 145.92631530761719 -43.223194122314453, 145.4830322265625 -42.650703430175781, 145.38616943359375 -42.464195251464844, 145.82795715332031 -42.501945495605469, 145.07258605957031 -41.577156066894531, 144.90054321289063 -40.845218658447266, 146.58587646484375 -41.291374206542969, 147.80001831054688 -41.147617340087891, 148.25955200195313 -40.902679443359375, 148.47319030761719 -41.075611114501953, 148.52291870117188 -41.788833618164062, 148.12933349609375 -42.806430816650391, 147.34538269042969 -43.239715576171875, 146.91639709472656 -43.704837799072266)), ((142.54121398925781 -10.898410797119141, 142.84793090820313 -11.07573413848877, 143.02713012695313 -11.901708602905273, 143.37675476074219 -12.104367256164551, 143.17445373535156 -12.517995834350586, 143.57481384277344 -12.796828269958496, 143.94683837890625 -14.448851585388184, 144.26838684082031 -14.575309753417969, 144.58901977539063 -14.352115631103516, 144.73284912109375 -14.650595664978027, 145.38800048828125 -15.030624389648438, 145.52920532226563 -16.473457336425781, 146.19784545898438 -17.49560546875, 146.12821960449219 -18.239631652832031, 146.52542114257813 -19.065319061279297, 147.61637878417969 -19.546205520629883, 148.17660522460938 20.079109191894531, 148.90739440917969 -20.185646057128906, 148.77070617675781 -20.637355804443359, 149.30514526367188 -21.04315185546875, 149.76042175292969 -22.415578842163086, 150.22093200683594 22.713462829589844, 150.1484375 -22.306673049926758, 150.89729309082031 -22.66114616394043, 151.00613403320313 -23.582916259765625, 151.93380737304688 -24.14051628112793, 152.27639770507813 24.724786758422852, 152.52163696289063 -24.800580978393555, 152.68940734863281 -25.296232223510742, 153.03501892089844 -25.454490661621094, 153.27273559570313 -26.210777282714844, 153.29037475585938 26.993001937866211, 153.14988708496094 -27.324020385742188, 153.60006713867188 -28.111736297607422, 153.69715881347656 -28.823896408081055, 153.14321899414063 -30.682428359985352, 153.17552185058594 31.401203155517578, 152.37985229492188 -32.859695434570312, 151.96830749511719 -32.987766265869141, 151.56816101074219 -33.503929138183594, 150.96563720703125 -35.236156463623047, 150.4251708984375 35.6771354675293, 150.18850708007813 -37.329910278320312, 149.91603088378906 -37.777362823486328, 148.24066162109375 -38.080898284912109, 147.02470397949219 -38.824363708496094, 146.50288391113281 38.876548767089844, 146.72958374023438 -39.163665771484375, 145.73957824707031 -38.70556640625, 145.70791625976563 -38.424533843994141, 145.17349243164063 -38.048786163330078, 144.61477661132813 38.228744506835938, 144.95124816894531 -38.438838958740234, 143.56846618652344 -38.9527587890625, 142.10769653320313 -38.41265869140625, 141.42892456054688 -38.439579010009766, 140.21568298339844 37.624660491943359, 140.02616882324219 -37.229286193847656, 140.02934265136719 -36.578449249267578, 139.64814758300781
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
-36.024333953857422, 139.57157897949219 -35.5973014831543, 138.5560302734375 35.8480339050293, 138.40083312988281 -35.739955902099609, 138.63349914550781 -35.535476684570312, 138.77128601074219 -34.910751342773438, 138.30516052246094 -34.339134216308594, 137.88699340820313 35.313907623291016, 137.15071105957031 -35.455646514892578, 137.31202697753906 -35.053794860839844, 137.70594787597656 -35.008373260498047, 137.71554565429688 -34.442138671875, 138.11616516113281 33.499790191650391, 138.39241027832031 -33.276569366455078, 138.0718994140625 -32.730152130126953, 138.02352905273438 -33.048313140869141, 137.66084289550781 -33.297161102294922, 137.27078247070313 33.934112548828125, 136.30978393554688 -34.514995574951172, 135.91609191894531 -35.190467834472656, 134.91389465332031 -33.347339630126953, 134.41212463378906 -33.240230560302734, 134.31146240234375 33.011432647705078, 134.44065856933594 -32.724918365478516, 134.04069519042969 -32.325000762939453, 133.32875061035156 -32.320106506347656, 132.90133666992188 -32.072917938232422, 132.38589477539063 32.131229400634766, 131.48382568359375 -31.617877960205078, 129.38905334472656 -31.781232833862305, 127.46874237060547 -32.364013671875, 126.26261138916016 -32.417392730712891, 124.45204925537109 33.127155303955078, 123.56221771240234 -34.025871276855469, 122.37458801269531 -34.161888122558594, 121.61318206787109 -33.953533172607422, 119.97515106201172 -34.103199005126953, 119.53349304199219 34.562080383300781, 118.87643432617188 -34.588871002197266, 118.41074371337891 -35.073368072509766, 117.99697875976563 -35.195281982421875, 116.45505523681641 -35.0837516784668, 115.25058746337891 34.405483245849609, 115.189453125 -33.737743377685547, 115.61216735839844 -33.749591827392578, 115.76168060302734 -33.558475494384766, 115.950927734375 -32.190639495849609, 115.26192474365234 30.786540985107422, 115.11587524414063 -29.680290222167969, 114.83406066894531 -28.885986328125, 114.16830444335938 -28.016206741333008, 114.12889099121094 -27.367696762084961, 113.23877716064453 26.145689010620117, 113.29524993896484 -26.040727615356445, 113.63665008544922 -26.555038452148438, 113.94303894042969 -26.649562835693359, 113.52482604980469 -25.673364639282227, 114.08432006835938 26.4920597076416, 114.29875946044922 -26.521648406982422, 114.25409698486328 -26.271642684936523, 114.38450622558594 -26.254417419433594, 114.38618469238281 -26.000068664550781, 113.58287048339844 24.596633911132812, 113.56556701660156 -24.26606559753418, 113.96568298339844 -23.464162826538086, 113.82909393310547 -22.548957824707031, 114.10423278808594 -22.02070426940918, 114.23101043701172 22.503608703613281, 114.43566131591797 -22.598531723022461, 114.66001129150391 -22.076744079589844, 116.62245941162109 -20.820150375366211, 117.80059051513672 -20.741361618041992, 118.17213439941406 20.454486846923828, 118.93798065185547 -20.300273895263672, 119.13991546630859 -20.007402420043945, 120.01618194580078 -20.100902557373047, 121.07581329345703 -19.659969329833984, 121.77999877929688 18.685775756835938, 122.40011596679688 -18.226715087890625, 122.28913879394531 -17.381425857543945, 122.94200134277344
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
-16.566312789916992, 123.62236785888672 -17.562946319580078, 123.71196746826172 17.092321395874023, 124.03050994873047 -17.231498718261719, 124.11570739746094 -16.957944869995117, 123.75660705566406 -16.678993225097656, 123.77950286865234 -16.373815536499023, 125.05001068115234 16.513069152832031, 124.54142761230469 -16.245037078857422, 124.62816619873047 -15.640926361083984, 124.89231109619141 -15.449649810791016, 125.31279754638672 -15.607682228088379, 125.35932159423828 14.7875337600708, 126.06686401367188 -14.677942276000977, 126.47202301025391 -14.054102897644043, 126.74971008300781 -14.333209991455078, 127.05709075927734 -13.766800880432129, 127.73275756835938 14.178533554077148, 128.16622924804688 -14.686156272888184, 128.26980590820313 -15.359770774841309, 128.66252136230469 -14.869436264038086, 129.40008544921875 -14.975923538208008, 129.8359375 15.261057853698731, 130.05227661132813 -14.802887916564941, 129.63021850585938 -14.288888931274414, 130.40965270996094 -13.467185020446777, 130.66716003417969 -12.741966247558594, 131.15493774414063 12.613780975341797, 131.06253051757813 -12.429638862609863, 131.23200988769531 -12.251283645629883, 131.74357604980469 -12.383670806884766, 132.95478820800781 -12.152227401733398, 132.71826171875 11.606078147888184, 132.22822570800781 -11.460931777954102, 132.40925598144531 -11.301631927490234, 133.13264465332031 -11.516201972961426, 133.76284790039063 -11.934375762939453, 134.96577453613281 12.0462007522583, 135.33218383789063 -12.369593620300293, 135.85267639160156 -12.171424865722656, 136.29487609863281 -12.558222770690918, 136.50227355957031 -12.494205474853516, 136.63816833496094 12.099803924560547, 136.9947509765625 -12.353300094604492, 136.67274475097656 -13.20579719543457, 136.03456115722656 -13.467802047729492, 136.168212890625 -13.874351501464844, 136.08430480957031 14.186027526855469, 135.66123962402344 -14.66370964050293, 135.62026977539063 -14.956218719482422, 136.89080810546875 -16.008792877197266, 137.27737426757813 -16.014326095581055, 138.4639892578125 16.825523376464844, 139.16641235351563 -16.976600646972656, 139.45198059082031 -17.414670944213867, 140.02192687988281 -17.744054794311523, 140.26387023925781 -17.813465118408203, 140.91120910644531 17.614999771118164, 141.33607482910156 -16.940177917480469, 141.91496276855469 -15.209720611572266, 141.67181396484375 -14.7398042678833, 141.87205505371094 -14.097315788269043, 141.71598815917969 13.792503356933594, 141.802490234375 -13.029497146606445, 142.12260437011719 -12.685539245605469, 141.88218688964844 -12.450845718383789, 142.32931518554688 -11.140419960021973, 142.54121398925781 10.898410797119141 )))',0); SELECT @Australia AS Australia; GO -- Script 19.9 Draw Australia with a buffer around it DECLARE @Australia geometry; SET @Australia = geometry::STGeomFromText('MULTIPOLYGON (((146.91639709472656 43.704837799072266, 145.92631530761719 -43.223194122314453, 145.4830322265625 -42.650703430175781, 145.38616943359375 -42.464195251464844, 145.82795715332031 -42.501945495605469,
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
145.07258605957031 -41.577156066894531, 144.90054321289063 -40.845218658447266, 146.58587646484375 -41.291374206542969, 147.80001831054688 -41.147617340087891, 148.25955200195313 -40.902679443359375, 148.47319030761719 -41.075611114501953, 148.52291870117188 -41.788833618164062, 148.12933349609375 -42.806430816650391, 147.34538269042969 -43.239715576171875, 146.91639709472656 -43.704837799072266)), ((142.54121398925781 -10.898410797119141, 142.84793090820313 -11.07573413848877, 143.02713012695313 -11.901708602905273, 143.37675476074219 -12.104367256164551, 143.17445373535156 -12.517995834350586, 143.57481384277344 -12.796828269958496, 143.94683837890625 -14.448851585388184, 144.26838684082031 -14.575309753417969, 144.58901977539063 -14.352115631103516, 144.73284912109375 -14.650595664978027, 145.38800048828125 -15.030624389648438, 145.52920532226563 -16.473457336425781, 146.19784545898438 -17.49560546875, 146.12821960449219 -18.239631652832031, 146.52542114257813 -19.065319061279297, 147.61637878417969 -19.546205520629883, 148.17660522460938 20.079109191894531, 148.90739440917969 -20.185646057128906, 148.77070617675781 -20.637355804443359, 149.30514526367188 -21.04315185546875, 149.76042175292969 -22.415578842163086, 150.22093200683594 22.713462829589844, 150.1484375 -22.306673049926758, 150.89729309082031 -22.66114616394043, 151.00613403320313 -23.582916259765625, 151.93380737304688 -24.14051628112793, 152.27639770507813 24.724786758422852, 152.52163696289063 -24.800580978393555, 152.68940734863281 -25.296232223510742, 153.03501892089844 -25.454490661621094, 153.27273559570313 -26.210777282714844, 153.29037475585938 26.993001937866211, 153.14988708496094 -27.324020385742188, 153.60006713867188 -28.111736297607422, 153.69715881347656 -28.823896408081055, 153.14321899414063 -30.682428359985352, 153.17552185058594 31.401203155517578, 152.37985229492188 -32.859695434570312, 151.96830749511719 -32.987766265869141, 151.56816101074219 -33.503929138183594, 150.96563720703125 -35.236156463623047, 150.4251708984375 35.6771354675293, 150.18850708007813 -37.329910278320312, 149.91603088378906 -37.777362823486328, 148.24066162109375 -38.080898284912109, 147.02470397949219 -38.824363708496094, 146.50288391113281 38.876548767089844, 146.72958374023438 -39.163665771484375, 145.73957824707031 -38.70556640625, 145.70791625976563 -38.424533843994141, 145.17349243164063 -38.048786163330078, 144.61477661132813 38.228744506835938, 144.95124816894531 -38.438838958740234, 143.56846618652344 -38.9527587890625, 142.10769653320313 -38.41265869140625, 141.42892456054688 -38.439579010009766, 140.21568298339844 37.624660491943359, 140.02616882324219 -37.229286193847656, 140.02934265136719 -36.578449249267578, 139.64814758300781 -36.024333953857422, 139.57157897949219 -35.5973014831543, 138.5560302734375 35.8480339050293, 138.40083312988281 -35.739955902099609, 138.63349914550781 -35.535476684570312, 138.77128601074219 -34.910751342773438, 138.30516052246094 -34.339134216308594, 137.88699340820313 35.313907623291016, 137.15071105957031 -35.455646514892578, 137.31202697753906 -35.053794860839844, 137.70594787597656 -35.008373260498047, 137.71554565429688 -34.442138671875, 138.11616516113281 33.499790191650391, 138.39241027832031 -33.276569366455078, 138.0718994140625 -32.730152130126953, 138.02352905273438 -33.048313140869141, 137.66084289550781 -33.297161102294922, 137.27078247070313 33.934112548828125,
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
136.30978393554688 -34.514995574951172, 135.91609191894531 -35.190467834472656, 134.91389465332031 -33.347339630126953, 134.41212463378906 -33.240230560302734, 134.31146240234375 33.011432647705078, 134.44065856933594 -32.724918365478516, 134.04069519042969 -32.325000762939453, 133.32875061035156 -32.320106506347656, 132.90133666992188 -32.072917938232422, 132.38589477539063 32.131229400634766, 131.48382568359375 -31.617877960205078, 129.38905334472656 -31.781232833862305, 127.46874237060547 -32.364013671875, 126.26261138916016 -32.417392730712891, 124.45204925537109 33.127155303955078, 123.56221771240234 -34.025871276855469, 122.37458801269531 -34.161888122558594, 121.61318206787109 -33.953533172607422, 119.97515106201172 -34.103199005126953, 119.53349304199219 34.562080383300781, 118.87643432617188 -34.588871002197266, 118.41074371337891 -35.073368072509766, 117.99697875976563 -35.195281982421875, 116.45505523681641 -35.0837516784668, 115.25058746337891 34.405483245849609, 115.189453125 -33.737743377685547, 115.61216735839844 -33.749591827392578, 115.76168060302734 -33.558475494384766, 115.950927734375 -32.190639495849609, 115.26192474365234 30.786540985107422, 115.11587524414063 -29.680290222167969, 114.83406066894531 -28.885986328125, 114.16830444335938 -28.016206741333008, 114.12889099121094 -27.367696762084961, 113.23877716064453 26.145689010620117, 113.29524993896484 -26.040727615356445, 113.63665008544922 -26.555038452148438, 113.94303894042969 -26.649562835693359, 113.52482604980469 -25.673364639282227, 114.08432006835938 26.4920597076416, 114.29875946044922 -26.521648406982422, 114.25409698486328 -26.271642684936523, 114.38450622558594 -26.254417419433594, 114.38618469238281 -26.000068664550781, 113.58287048339844 24.596633911132812, 113.56556701660156 -24.26606559753418, 113.96568298339844 -23.464162826538086, 113.82909393310547 -22.548957824707031, 114.10423278808594 -22.02070426940918, 114.23101043701172 22.503608703613281, 114.43566131591797 -22.598531723022461, 114.66001129150391 -22.076744079589844, 116.62245941162109 -20.820150375366211, 117.80059051513672 -20.741361618041992, 118.17213439941406 20.454486846923828, 118.93798065185547 -20.300273895263672, 119.13991546630859 -20.007402420043945, 120.01618194580078 -20.100902557373047, 121.07581329345703 -19.659969329833984, 121.77999877929688 18.685775756835938, 122.40011596679688 -18.226715087890625, 122.28913879394531 -17.381425857543945, 122.94200134277344 -16.566312789916992, 123.62236785888672 -17.562946319580078, 123.71196746826172 17.092321395874023, 124.03050994873047 -17.231498718261719, 124.11570739746094 -16.957944869995117, 123.75660705566406 -16.678993225097656, 123.77950286865234 -16.373815536499023, 125.05001068115234 16.513069152832031, 124.54142761230469 -16.245037078857422, 124.62816619873047 -15.640926361083984, 124.89231109619141 -15.449649810791016, 125.31279754638672 -15.607682228088379, 125.35932159423828 14.7875337600708, 126.06686401367188 -14.677942276000977, 126.47202301025391 -14.054102897644043, 126.74971008300781 -14.333209991455078, 127.05709075927734 -13.766800880432129, 127.73275756835938 14.178533554077148,
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
128.16622924804688 -14.686156272888184, 128.26980590820313 -15.359770774841309, 128.66252136230469 -14.869436264038086, 129.40008544921875 -14.975923538208008, 129.8359375 15.261057853698731, 130.05227661132813 -14.802887916564941, 129.63021850585938 -14.288888931274414, 130.40965270996094 -13.467185020446777, 130.66716003417969 -12.741966247558594, 131.15493774414063 12.613780975341797, 131.06253051757813 -12.429638862609863, 131.23200988769531 -12.251283645629883, 131.74357604980469 -12.383670806884766, 132.95478820800781 -12.152227401733398, 132.71826171875 11.606078147888184, 132.22822570800781 -11.460931777954102, 132.40925598144531 -11.301631927490234, 133.13264465332031 -11.516201972961426, 133.76284790039063 -11.934375762939453, 134.96577453613281 12.0462007522583, 135.33218383789063 -12.369593620300293, 135.85267639160156 -12.171424865722656, 136.29487609863281 -12.558222770690918, 136.50227355957031 -12.494205474853516, 136.63816833496094 12.099803924560547, 136.9947509765625 -12.353300094604492, 136.67274475097656 -13.20579719543457, 136.03456115722656 -13.467802047729492, 136.168212890625 -13.874351501464844, 136.08430480957031 14.186027526855469, 135.66123962402344 -14.66370964050293, 135.62026977539063 -14.956218719482422, 136.89080810546875 -16.008792877197266, 137.27737426757813 -16.014326095581055, 138.4639892578125 16.825523376464844, 139.16641235351563 -16.976600646972656, 139.45198059082031 -17.414670944213867, 140.02192687988281 -17.744054794311523, 140.26387023925781 -17.813465118408203, 140.91120910644531 17.614999771118164, 141.33607482910156 -16.940177917480469, 141.91496276855469 -15.209720611572266, 141.67181396484375 -14.7398042678833, 141.87205505371094 -14.097315788269043, 141.71598815917969 13.792503356933594, 141.802490234375 -13.029497146606445, 142.12260437011719 -12.685539245605469, 141.88218688964844 -12.450845718383789, 142.32931518554688 -11.140419960021973, 142.54121398925781 10.898410797119141 )))',0); SELECT @Australia.STBuffer(1) UNION ALL SELECT @Australia; GO
3.
Review the results from each script. Remember to click on the Spatial results tab to see the output. Query Number 19.1 19.2 Query Title Draw a square. Try an invalid value - note the 6522 error and the wrapped error message. Draw a more complex shape. Output A square is drawn. A .NET error is returned. Scroll to the right to read the full message. Note how specific the message is. The shape is drawn. Note how a polygon is represented in text in the query.
19.3
10
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
Query Title Multiple shapes. Intersecting shapes. Union of two shapes. Intersection of shapes.
Output Two shapes are drawn. The shapes are moved to intersect. A combined shape is drawn. The two intersecting shapes and the intersection are drawn. Australian map is drawn. Note the calculation of a buffer region around the map.
19.8 19.9
3.
3.
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
11
3.
3.
12
Lab Answer Key: Working with SQL Server 2008 R2 Spatial Data
END; GO
3.
3.
Module 20
Lab Answer Key: Working with Full-Text Indexes and Queries
Contents:
Exercise 1: Implement a full-text index Exercise 2: Implement a stoplist Challenge Exercise 3: Create a stored procedure to implement a full-text search (Only if time permits) 5 2 4
2.
3.
3.
3.
In the toolbar, click Execute. Note that a warning might be returned when you execute the above command, even though the command executed successfully. If a warning appears, it can be ignored.
3. 4.
In the toolbar, click Execute. Re-execute the query until the has_crawl_completed column shows the value 1.
3.
3.
3.
3.
In the toolbar, click Execute. A list of system stop words for the English language is returned.
3.
3.
3.
Challenge Exercise 3: Create a stored procedure to implement a full-text search (Only if time permits)
Task 1: Review the supporting documentation
1. Review the supporting documentation for specification for a new stored procedure.
ft.RANK AS Ranking FROM Marketing.ProductDescription AS d INNER JOIN FREETEXTTABLE(Marketing.ProductDescription, Description, @PhraseToSearch) AS ft ON d.ProductDescriptionID = ft.[KEY] WHERE d.LanguageID = 'en' ORDER BY ft.RANK DESC; END; GO EXEC Marketing.GetRelevantDescriptions 'strong frame'; GO EXEC Marketing.GetRelevantDescriptions 'serious competition'; GO
3.
In the toolbar, click Execute. Note: The first query returns twenty rows. The second query returns five rows.