OFFICIAL

MICROSOFT

LEARNING

PRODUCT

6232A
Lab Instructions and Answer Key: Implementing a Microsoft® SQL Server® 2008 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. © 2008 Microsoft Corporation. All rights reserved. Microsoft, Excel, IntelliSense, Internet Explorer, MS, MSDN, PowerPoint, SQL Server, Visual Basic, Visual C#, Visual C++, Visual Studio, Windows and Windows Server 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.

Technical Reviewer: Geoff Black Product Number: 6232A Part Number X15-01555 Released: 11/2008

Lab Instructions: Creating Databases and Database Files

1

Module 1
Lab Instructions: Creating Databases and Database Files
Contents:
Exercise 1: Creating a Database Exercise 2: Creating a Schema Exercise 3: Creating a Database Snapshot 2 4 5

the primary filegroup and a filegroup named SECONDARY. The database should use two filegroups. which should be the default filegroup. To do this you will create a new database and create a SQL Server Management Studio Scripts project with the following specifications: • • The new database name is AW_IT_Assets. The database should consist of two data files and one log file with the names AW_IT_Assets_Data1. • . AW_IT_Assets_Data2. You must first use the specification to create the database with the necessary options and create the appropriate filegroups. The AW_IT_Assets_Data2 file should be placed in the SECONDARY filegroup. and AW_IT_Assets_log. These files should be created in the E:\MOD01\Labfiles folder.2 Lab Instructions: Creating Databases and Database Files Lab: Creating Databases and Database Files Exercise 1: Creating a Database Scenario The senior database developer at Adventure Works has created a specification for a new database in which details of the information technology (IT) assets used by the company will be stored.

Start 6232A-NY-SQL-01.Lab Instructions: Creating Databases and Database Files 3 • Both data files should have an initial size of 20 megabytes (MB) each and should not grow automatically. Create a new database by executing a SQL Server Management Studio Scripts project. All scripts should be saved in a SQL Server Scripts project in the E:\MOD01\Labfiles\Scripts folder. The database should automatically close when no users are connected and should automatically shrink when appropriate. • • The main tasks for this exercise are as follows: 1. Create a SQL Server Management Studio Scripts project. The log file should have an initial size of 5 MB and should not grow automatically. 2. Save these scripts in a SQL Server Scripts project in the E:\MOD01\Labfiles folder. you should have created a new database with the appropriate options and filegroups and created a SQL Server Management Studio Scripts project. and log on as Student with the password of Pa$$w0rd. . Results: After this exercise. Task 1: Create a SQL Server Management Studio Scripts project 1. Create the AW_IT_Assets database based on the specifications provided. Task 2: Create a new database by executing a SQL Server Management Studio Scripts project • • Use the Generate Scripts Wizard to create a script of the database created in Task 1. 2.

you should have created a schema and assigned ownership to a user. Do not grant Katie any permissions in the Database User window. as permissions will be added in the next task. Display ownership of a schema.4 Lab Instructions: Creating Databases and Database Files Exercise 2: Creating a Schema Scenario The senior database developer is now requesting that access to the new database being used by the company be granted to a new user. The user NY-SQL-01\Katie should use the TechSupport schema as her default schema. 3. 3. Create a schema and assign ownership to a user. The main tasks for this exercise are as follows: 1 2. In this exercise you will now create the required schemas for the new AW_IT_Assets database. Results: After this exercise. Task 3: Display ownership of a schema 1. Task 1: Create a new database user • • Create a new database user named Katie. Execute the T-SQL statement. You should have also displayed ownership of the newly created schema. Create a T-SQL statement that displays ownership of the TechSupport schema. Task 2: Create a schema and assign ownership to a user • • The database should have one user-defined schema named TechSupport. Create a new database user. . 2. Comment the T-SQL statement to explain what it will do on execution.

Create a database snapshot. Using T-SQL. 2.Hardware table on the AW_IT_Assets database. Task 1: Create a database snapshot • • • A database snapshot named AW_IT_Assets_Snapshot1 must be created for reporting purposes. change the current database. Alter the database. The main tasks for this exercise are as follows: 1. Revert the database to the previously created database snapshot. alter the database.Lab Instructions: Creating Databases and Database Files 5 Exercise 3: Creating a Database Snapshot Scenario The senior developer at Adventure Works is now requesting a database snapshot be created for reporting purposes. Delete the TechSupport schema on the AW_IT_Assets database. 3. and then revert the database to the previously created snapshot. The files for the database snapshot must be created in the E:\MOD01\Labfiles\Snapshots folder. and then restore the database from the snapshot to undo those changes. In this exercise you will create a database snapshot. . Task 2: Alter the database • • Delete the TechSupport. create a snapshot of the AW_IT_Assets database. You will use T-SQL to write a statement that will create a database snapshot.

Results: After this exercise. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. you should have created a database snapshot. Lab Shutdown After you complete the lab. . Notice that the TechSupport. and then reverted the database to the database snapshot.Hardware table and TechSupport schema have both been restored. Revert the database to the AW_IT_Assets_Snapshot1 database snapshot. altered the database.6 Lab Instructions: Creating Databases and Database Files Task 3: Revert the database to the previously created database snapshot • • • Create a T-SQL statement to revert the AW_IT_Assets database.

Lab Instructions: Creating Data Types and Tables 1 Module 2 Lab Instructions: Creating Data Types and Tables Contents: Exercise 1: Creating Data Types Exercise 2: Using New Date and Time Data Types Exercise 3: Creating Tables Exercise 4: Creating Partitioned Tables 2 4 5 6 .

In addition. . the senior database developer has designed some new data types for the returns and refunds data and has assigned you the task of creating them in the database. Create a data type based on the decimal system-supplied data type. 2. The main tasks for this exercise are as follows: 1.2 Lab Instructions: Creating Data Types and Tables Lab: Creating Data Types and Tables Exercise 1: Creating Data Types Scenario The sales manager at Adventure Works has requested that the company’s database be modified to include data about goods that have been returned and sales that have been refunded. Create a data type based on the nvarchar system-supplied data type.

. you should have successfully created a new data type based on the nvarchar system-supplied data type. This data type should be based on the nvarchar system-supplied data type and should have a maximum length of 100 characters. Create a new data type named ShortDescription in the dbo schema. Task 2: Create a data type based on the decimal system-supplied data type • • Create a new data type named CashValue in the dbo schema. Results: After this exercise. This data type should be based on the decimal system-supplied data type and should have a precision of 8 and a scale of 2. You should have also successfully created a new data type based on the decimal system-supplied data type.Lab Instructions: Creating Data Types and Tables 3 Task 1: Create a data type based on the nvarchar system-supplied data type • • • Start 6232A-NY-SQL-01. and log on as Student with the password of Pa$$w0rd.

2. The senior database developer at Adventure Works has designed data type conversions for the company's calendar data and has assigned you the task of reporting back with what the different output types will look like. You will then convert sample data into the datetime format as a test of the new data type conversions. datetime. Use CAST and CONVERT to convert sample data into the date format and also into the time format. Task 1: Obtain date and time formatting using T-SQL • • Write a query using CAST and CONVERT to convert the time period of 200705-08 12:35:29 to multiple data formats.4 Lab Instructions: Creating Data Types and Tables Exercise 2: Using New Date and Time Data Types Scenario The sales manager at Adventure Works has requested that the company's database next be modified to show calendar data using a new format. you should have successfully obtained date and time formatting using T-SQL and then converted sample data into the date and time formats using T-SQL. Obtain date and time formatting using T-SQL.997' as your datetime sample. Results: After this exercise. Task 2: Convert sample data into new data type formats using T-SQL • • Use '2006-04-04T15:50:59. and datetimeoffset data types in your query. Be sure to include the conversion to time. The main tasks for this exercise are as follows: 1. datetime2. Convert sample data into new data type formats using T-SQL. . smalldatetime. date.

Create a table named ReturnedGoods. you should have created a table named ReturnedGoods. . ReturnReason. The table must contain the following columns: • • • • • ReturnID. An int column that cannot contain NULL values. An int column that cannot contain NULL values. Results: After this exercise. CustomerID.Lab Instructions: Creating Data Types and Tables 5 Exercise 3: Creating Tables Scenario The sales department at Adventure Works needs two new tables to hold new data on returned goods and refunds paid. An int column that cannot contain NULL values. ProductID. ReturnDate. Task 1: Create a table named ReturnedGoods • • The table must be created in the Sales schema. 2. An int identity column that cannot contain NULL values. Task 2: Create a table named Refunds • • The table must be created in the Sales schema. The Refunds table should contain the following columns: • • • RefundID. created a table named Refunds. Amount. A ShortDescription column that can contain NULL values. and followed all provided specifications. ReturnID. The main tasks for this exercise are as follows: 1. A datetime column that cannot contain NULL values. The senior database developer has given you the task of creating these two tables based on the specifications provided. Create a table named Refunds. A CashValue column that cannot contain NULL values. An int identity column that cannot contain NULL values.

An int column that cannot contain NULL values. 3. Prepare the database for partitioning. Create a partitioned table named ReturnsArchive. Execute the query. ReturnReason. A ShortDescription column that can contain NULL values. Task 2: Create a partitioned table named ReturnsArchive • • Create a partitioned table that stores data in four partitions using the Test1FG. specifically that the working with the Returns table is very slow. A datetime column that cannot contain NULL values. An int identity column that cannot contain NULL values. CustomerID. 2. . As part of the solution to this problem.6 Lab Instructions: Creating Data Types and Tables Exercise 4: Creating Partitioned Tables Scenario The Director of IT at Adventure Works has received several complaints about database performance. Task 1: Prepare the database for partitioning • • Open the query located at E:\MOD02\Labfiles\Scripts\partition_prep. the senior database developer has tasked you with the creation of a partitioned table that will be used to archive returns data at a later date. and Test4FG filegroups. The table must contain the following columns: • • • • • ReturnID. ProductID. The main tasks for this exercise are as follows: 1. An int column that cannot contain NULL values. Test2FG. ReturnDate. Test3FG. Review the partitioning implementation.sql.

Lab Instructions: Creating Data Types and Tables 7 Task 3: Review the partitioning implementation • • Review the Storage settings in the AdventureWorksDW2008 table properties. Lab Shutdown After you complete the lab. you should have successfully prepared the database for partitioning. Filegroups. Results: After this exercise. created a partitioned table named ReturnsArchive according to the specifications provided. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. . and then reviewed the partitioning changes. and Partitioning. Note the new partitioning information under Compression.

Lab Instructions: Creating and Tuning Indexes 1 Module 3 Lab Instructions: Creating and Tuning Indexes Contents: Exercise 1: Creating Indexes Exercise 2: Optimizing Indexes 2 4 .

ReorderPoint. SafetyStockLevel Included columns: DaysToManufacture Locking: Allow row locks but not page locks. Use the following settings: • • • • Key columns: ProductNumber. . You must implement a new unique. Color.2 Lab Instructions: Creating and Tuning Indexes Lab: Creating and Optimizing Indexes Exercise 1: Creating Indexes Scenario • • You must use SQL Server Management Studio to create a SQL Server Scripts project for the modifications in the E:\MOD03\Labfiles\Starter folder.Product table to support queries that include stock-level management information. Fill factor: Set the fill factor to 90 percent on both leaf and non-leaf nodes. non-clustered index named Ix_Product_Supply_Chain on the Production.

Lab Instructions: Creating and Tuning Indexes 3 This exercise’s main tasks are: 1. Task 2: Create a SQL Server Scripts project 1. . Open SQL Server Management Studio. enter the Transact-SQL code to create the Ix_Product_Supply_Chain index on Production. Make sure to allow row locks. Task 3: Create the Ix_Product_Supply_Chain index 1. Start the 6432A-NY-SQL-01 virtual machine and log on as Student. Select the SQL Server Scripts template and enter the name and location for the project (E:/MOD03/Labfiles/Starter). click New. ReorderPoint. and SafetyStockLevel. 2. and log on as Student with the password of Pa$$w0rd. In the query window. Color.Product. Create a SQL Server Scripts project. columns ProductNumber. On the File menu. use a FILLFACTOR of 90. 3. Include DaysToManufacture. you should have successfully created a SQL Server Scripts project and created the Ix_Product_Supply_Chain index. 2. 3. 2. On the toolbar. and then click Project. click Execute. Create the Ix_Product_Supply_Chain index. Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as Student • Start 6232A-NY-SQL-01. and pad the index. Results: After this exercise. and connect to the server you want to manage (NY-SQL-01). do not allow page locks.

Rebuild AK_Product_Name. and then execute it.Product table of the AdventureWorks2008 database. . open aw2008sampleproductadd. Task 1: Add the sample products to the database • In SQL Server Management Studio.4 Lab Instructions: Creating and Tuning Indexes Exercise 2: Optimizing Indexes Scenario You have been asked to add 1000 new sample products to the Adventure Works 2008 database. Reorganize AK_Product_ProductNumber. Add the sample products to the database. you need to check the indexes for fragmentation and reorganize or rebuild as needed. 2. A script has been provided to add these records. 3. This exercise’s main tasks are: 1. Task 2: Reorganize AK_Product_ProductNumber • Use SQL Server Management Studio to reorganize the AK_Product_ProductNumber index which is associated to the Production.sql from the E:\Mod03\Labfiles\Starter\ folder. o You may ignore any errors about duplicate keys. After you add the records.

Product table of the AdventureWorks2008 database. . you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.Product table indexes using both reorganize and rebuild. Lab Shutdown After you complete the lab. you should have successfully optimized the Production. Results: After this exercise.Lab Instructions: Creating and Tuning Indexes 5 Task 3: Rebuild AK_Product_Name • Use SQL Server Management Studio to reorganize the AK_Product_Name index which is associated to the Production.

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers 1 Module 4 Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers Contents: Exercise 1: Creating Constraints Exercise 2: Disabling Constraints Exercise 3: Creating Triggers 2 5 7 .

2

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

Lab: Implementing Data Integrity by using Constraints and Triggers

Exercise 1: Creating Constraints
Scenario
After consulting with the Human Resources team, the senior database developer has decided a new table is required to store this historical information. The senior database developer has asked you to: • • • • Create a new table named HumanResources.JobCandidateHistory. The JobCandidateHistory table will have the following columns and constraints: JobCandidateID. An int column that cannot contain null values. The values in the column must be unique. Rating. An int column that cannot contain null values. The values in this column must be within the range 1 through 10, with a default value of 5. RejectedDate. A datetime column that cannot contain null values.

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

3

BusinessEntityID. An int column that can contain null values. This column is a foreign key to the BusinessEntityID column in the Person.BusinessEntity table. Create a SQL Server Scripts project for the modifications by using SQL Server Management Studio, and then store the project in the E:\MOD04\Labfiles\Starter folder.

This exercise’s main tasks are: 1. 2. 3. 4. Start the 6232A-NY-SQL-01 virtual machine and log on as Student. Create a SQL Server Scripts project. Create the JobCandidateHistory table and constraints. Test the JobCandidateHistory table and constraints.

Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as Student
• Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd.

Task 2: Create a SQL Server Scripts project
1. 2. 3. Open SQL Server Management Studio, and connect to the server you want to manage (NY-SQL-01). On the File menu, click New, and then click Project. Select the SQL Server Scripts template and enter the name and location for the project (E:/MOD04/Labfiles/Starter).

Task 3: Create the JobCandidateHistory table and constraints
1. In the query window, type the appropriate Transact-SQL statement to create the HumanResources.JobCandidateHistory table in the AdventureWorks database. Execute the query, and then save the query file. Use Object Explorer to verify that the table and constraints have been created.

2 3.

4

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

Task 4: Test the JobCandidateHistory table and constraints
1. 2. 3. In SQL Server Management Studio, open the TestConstraints.sql script file in the E:\MOD04\Labfiles\Starter folder. Use the INSERT statement to test inserting invalid data. Use the INSERT statement to test inserting valid data.
Results: After this exercise, you should have successfully created a SQL Server Scripts project, created the HumanResources.JobCandidateHistory table, and tested the constraints.

2. In the query window.JobCandidateHistory table. Task 2: Disable constraints on the JobCandidateHistory table 1. Execute the query. Open the InsertTestData. Enable constraints on the JobCandidateHistory table. and then save the query file.Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers 5 Exercise 2: Disabling Constraints. Change the query file name to Constraints.sql. Disable constraints on the JobCandidateHistory table.sql script. open InsertTestData. 4. Insert multiple rows into the JobCandidateHistory table. Task 1: Insert multiple rows into the JobCandidateHistory table • In SQL Server Management Studio. This exercise’s main tasks are: 1. type the appropriate Transact-SQL to disable the constraints on the HumanResources. 3. Add a new query to the project. and then execute it with statistics enabled. 2. and then compare the results. you need to test the effect on performance by running a test script against the table with constraints both enabled and disabled. and then compare the performance statistics for the INSERT statements before and after the constraints were disabled. 3. . execute the query. Examine the performance statistics. Scenario Now that you have enabled constraints on your table.sql from the E:\Mod04\Labfiles\Starter\ folder.

Results: After this exercise. 2. and then save the query file.sql query window. In the Constraints.JobCandidateHistory table. type the appropriate Transact-SQL to enable the constraints on the HumanResources. Execute the query.6 Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers Task 3: Enable constraints on the JobCandidateHistory table 1. . you should have successfully compared performance results with constraints enabled and disabled.

type the appropriate Transact-SQL to create the dJobCandidate trigger on the HumanResources.JobCandidate table in the AdventureWorks database. In the query window. Use Object Explorer to verify that the trigger has been created. Change the query file name to Trigger. 4.Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers 7 Exercise 3: Creating Triggers. . Test the dJobCandidate trigger. 3. Execute the query. and ContactDetails should be set to NULL.JobCandidateHistory table when somebody deletes a candidate. Scenario To further assist in maintaining historical information about job candidates for the Human Resources department. the senior database developer has asked you to create a new DELETE trigger named dJobCandidate on the HumanResources. Rating should be left at its default value.JobCandidate table that copies the candidate’s information to the HumanResources. Create the dJobCandidate trigger. 2.sql. and then save the query file. Add a new query to the project. 2. This exercise’s main tasks are: 1. Task 1: Create the dJobCandidate trigger 1. The JobCandidateId column must be copied directly across and the RejectedDate set to the current date by using the getdate function.

you should have successfully created and tested the dJobCandidate trigger. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. In SQL Server Management Studio. Results: After this exercise. . Execute the query script. 2.JobCandidateHistory table.8 Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers Task 2: Test the dJobCandidate trigger 1.JobCandidate table has been inserted into the HumanResources.sql query file from the E:\MOD04\Labfiles\Starter folder. and look in the results pane to verify that the record deleted from the HumanResources. open the TestTrigger. Lab Shutdown After you complete the lab.

Lab Instructions: Using XML 1 Module 5 Lab Instructions: Using XML Contents: Lab 5A: Using XML Exercise 1: Mapping Relational Data and XML Exercise 2: Storing XML Natively in the Database Lab 5B: Using XML Exercise 3: Using XQuery with XML Methods Exercise 4: Creating XML Indexes 12 15 2 8 .

You must modify the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML. This system is still in the initial testing phase. You must create the appropriate Transact-SQL required to store the XML order details in the existing database tables. Adventure Works is also creating a new ordering system for specific customers so that they can send orders as XML documents. You must also write Transact-SQL code for a delivery scheduling application that retrieves information from the XML data and modifies the information by using xml methods.2 Lab Instructions: Using XML Lab 5A: Using XML Exercise 1: Mapping Relational Data and XML Scenario Adventure Works currently generates order manifests by performing a query in the AdventureWorks database. The organization intends to deploy a new Pocket PC– based application to its warehouse employees. The item-choosing application requires the order manifest to be downloaded as XML. which they will then use when picking items from the warehouse for an order delivery. .

Lab Instructions: Using XML 3 The senior database developer has provided you with the following requirements for the modifications: Two different FOR XML queries are required to produce two different XML formats. as shown in the following example: <SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item ProductID="776" OrderQty="1" /> <Item ProductID="777" OrderQty="3" /> <Item ProductID="778" OrderQty="1" /> <Item ProductID="771" OrderQty="1" /> <! -. The first FOR XML query should produce attribute-centric XML.remaining items go here. as shown in the following example: <SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item> <ProductID>776</ProductID> <OrderQty>1</OrderQty> </Item> <Item> <ProductID>777</ProductID> <OrderQty>3</OrderQty> </Item> <Item> <ProductID>778</ProductID> <OrderQty>1</OrderQty> </Item> <Item> <!-. The Item attributes and elements come from the Sales. --> </SalesOrder> The second FOR XML query should produce a mixture of element-centric and attribute-centric XML.more items here --> </SalesOrder> In the FOR XML queries.SalesOrderHeader table. the SalesOrder attributes come from the Sales. .SalesOrderDetail table.

The first query will insert data into the Sales. .SalesOrderDetail table and should use the following schema declaration: Column name OrderQty ProductID UnitPrice Data type Int Int Money A set of five queries are required that use xml methods to retrieve and modify the delivery schedule information. Note: XML is case sensitive.4 Lab Instructions: Using XML Two OPENXML queries are required to shred the XML document into the appropriate tables.SalesOrderHeader table and should use the following schema declaration: Column name CustomerID OrderDate DueDate AccountNumber ContactID BillToAddressID ShipToAddressID ShipMethodID SubTotal TaxAmt Data type int datetime datetime nvarchar(15) int int int int money money The second OPENXML query will insert data into the Sales. so attention needs to be placed on casing of the characters when completing these labs.

SalesOrderDetail Item WHERE SalesOrder.ssmssln. .SalesOrderID FOR XML AUTO. SalesOrder. Start the Server Management Studio and connect to the server.SalesOrderID. SalesOrder.SalesOrderID.SalesOrderID = Item.AccountNumber. (SELECT Item. Item.SalesOrderID = Item.SalesOrderID = 43659 FOR XML AUTO • Execute the modified code and examine the XML data.OrderQty FROM Sales. SELECT SalesOrder.OrderDate.SalesOrderHeader SalesOrder JOIN Sales.SalesOrderID WHERE SalesOrder.SalesOrderHeader SalesOrder WHERE SalesOrder.OrderQty FROM Sales. SalesOrder.ProductID.OrderDate.SalesOrderDetail Item ON SalesOrder. Modify the query statement.SalesOrderID = 43659 FOR XML AUTO • • Execute the modified code and examine the XML data. Modify the SELECT statement to include the FOR XML clause and return attribute-centric XML by using AUTO mode. ELEMENTS. Item.AccountNumber. SELECT SalesOrder. TYPE) FROM Sales. Execute the FORXML. Item. Open the project XML. SalesOrder.sql query.Lab Instructions: Using XML 5 Task 1: Create the FOR XML queries to return the order manifest documents • • • • • Start 6232A-NY-SQL-01 and logon as Student using the password Pa$$w0rd.ProductID.

ProductID int. AccountNumber nvarchar(15). 1) WITH ( CustomerID int. Locate the comment Call stored procedure to create the memory tree. TaxAmt money) • Locate the comment Add OPENXML function for SalesOrderDetail table INSERT. @doc • Locate the comment Add OPENXML function for SalesOrderHeader table INSERT. '/SalesOrder/Item'. SubTotal money. and then add an OPENXML function to retrieve the relevant attributes from the SalesOrder node. and then add an OPENXML function to retrieve the relevant subelements from the Item node. DueDate datetime. OPENXML(@docHandle. '/SalesOrder'.sql query. OrderDate datetime. ShipToAddressID int.6 Lab Instructions: Using XML Task 2: Use the OPENXML function to insert the XML data into the tables • • Open the OPENXML. EXEC sp_xml_preparedocument @docHandle OUTPUT. UnitPrice money) . ShipMethodID int. and then add a call to the sp_xml_preparedocument stored procedure. BillToAddressID int. SalesPersonID int. OPENXML(@docHandle. 2) WITH ( OrderQty int.

and then add a call to the sp_xml_removedocument stored procedure. and confirm that a new record was added to the SalesOrderHeader table and two records were added to the SalesOrderDetail table. .Lab Instructions: Using XML 7 • Locate the comment Call stored procedure to clean up memory tree. EXEC sp_xml_removedocument @docHandle • Execute the code and examine the results. Results: After this exercise. you should have modified the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML.

The senior database developer has asked you to: • Create an XML schema collection named HumanResources. the senior database developer has decided a new table is required to store this historical information. A file named HistoricResumeSchema. • • Name: Job Candidate History Location: E:\Mod05\Labfiles\Starter .JobCandidateHistory table. • • Task 1: Create a SQL Server Scripts project in SQL Server Management Studio • Create a new project. The senior database developer has provided you with the Transact-SQL to create the HumanResources. The Human Resources department will supply the XML schema. Apply the schema collection to the JobCandidateHistory.Resume column to make it typed xml data. which is a variant of the schema that the department currently uses for the resumes of active candidates.xml containing the schema for the HistoricResumeSchemaCollection XML schema collection is provided in the E:\Mod05\Labfiles\Starter folder.HistoricResumeSchemaCollection. Create a SQL Server Scripts project for the modifications by using SQL Server Management Studio.8 Lab Instructions: Using XML Exercise 2: Storing XML Natively in the Database Scenario The Human Resources department has decided that it wants to keep a historical record of job candidates so that it can contact past unsuccessful candidates if new positions come up. and compare the information provided by candidates if they apply for different positions over time. and then store the project in the E:\Mod05\Labfiles\Starter folder. After consulting with the Human Resources team.

sql Task 4: Create an XML schema collection named HumanResources. Resume xml ) GO • • Execute the code.xml Examine this file.HistoricResumeSchemaCollection • Add this item to the solution. ModifiedDate DateTime. Task 3: Create a new query file • Create a new query file. . NationalIDNumber nvarchar (15) NOT NULL.JobCandidateHistory ( JobCandidateID int IDENTITY PRIMARY KEY.JobCandidateHistory table • Create a table named HumanResources. Verify that the necessary columns have been successfully created. BusinessEntityID int NULL. • File name: XMLSchema. and then verify that the HumanResources. • • • • File of type: XML Files Folder: E:\Mod05\Labfiles\Starter File name: HistoricResumeSchema.JobCandidateHistory table is listed. Rating int NOT NULL Default (5).JobCandidateHistory in the AdventureWorks2008 database.Lab Instructions: Using XML 9 Task 2: Create the HumanResources. USE AdventureWorks2008 GO CREATE TABLE HumanResources. RejectedDate datetime NOT NULL.

HistoricResumeSchemaCollection) GO • • Execute the code and examine Messages box and verify that the script completed without any errors. Below the comment This should fail.sql Enter the following code to alter the JobCandidateHistory table: ALTER TABLE HumanResources. • File name: AlterCandidateTable. . Below the comment This should succeed. Task 5: Apply the schema collection to the JobCandidateHistory. Execute the code and examine the error message in the Messages pane. Examine Messages box and verify that the script completed without any errors.HistoricResumeSchemaCollection is associated with the Resume column. Execute the code. Confirm that the HumanResources. Execute the code and verify that the script completed without any errors.10 Lab Instructions: Using XML • Add this item to the solution.JobCandidateHistory ALTER COLUMN Resume xml (HumanResources.Resume column • • Create a new query.sql file. Task 6: Test the HistoricResumeSchema XML schema • • • • • Open the TestXMLSchema. • • • File of type: SQL Server files Folder: E:\Mod05\Labfiles\Starter File name: CreateXMLSchema. select the code. select the INSERT code.sql • • Examine this file.

sql file. Open the SelectCandidates. Task 7: Populate the HumanResources. Execute the code and verify that the script completed without any errors.JobCandidateHistory GO • • Execute the code and verify that the script completed without any errors. Examine the XML record to confirm that it is complete and accurate. the student has created and applied an XML schema and stored XML natively in the database. Results: After this exercise. • File name: SelectCandidates.Lab Instructions: Using XML 11 • • Create a new query. Examine the xml record to confirm that it is accurate. Execute the code and verify that the script completed without any errors.sql file.JobCandidateHistory table with additional sample data • • • • • Open the AddCandidate. .sql Enter the following code: USE AdventureWorks2008 GO SELECT * FROM HumanResources.

12 Lab Instructions: Using XML Lab 5B: Using XML Exercise 3: Using XQuery with XML Methods Scenario Adventure Works currently generates order manifests by performing a query in the AdventureWorks database. Adventure Works is also creating a new ordering system for specific customers so that they can send orders as XML documents. which they will then use when picking items from the warehouse for an order delivery. This system is still in the initial testing phase. The organization intends to deploy a new Pocket PC– based application to its warehouse employees. . You must modify the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML. You must create the appropriate Transact-SQL required to store the XML order details in the existing database tables. The item-choosing application requires the order manifest to be downloaded as XML.

JobCandidateHistory WHERE JobCandidateID = 2 GO • Execute the statements. Task 2: Retrieve the address for a specified candidate • Below the SELECT statement. Task 1: Retrieve the resume elements • • Create a new query.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT NationalIDNumber.Street)[1]'.query(' /RES:Resume/RES:Name ') as Result FROM HumanResources.JobCandidateHistory GO • Execute the code and verify that the desired results are returned. Resume. • File name: xmlMethods.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT Resume.microsoft.sql Enter the following code to retrieve the resume elements: USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas. 'nvarchar(100)') As ResumeAddress FROM HumanResources. You need to use XQuery expressions to retrieve and modify delivery schedule data. and then verify that the desired results are returned. type the following Transact-SQL: USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.value( '(/RES:Resume/RES:Address/RES:Addr. .microsoft.Lab Instructions: Using XML 13 You must also write Transact-SQL code for a delivery scheduling application that retrieves information from the XML data and modifies the information by using xml methods.

Results: After this exercise.microsoft. type the following Transact-SQL: USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.modify('replace value of (/RES:Resume/RES:Address/RES:Addr. Rockhampton"') WHERE JobCandidateID = 2 GO • Execute the statements. and then verify that the desired results are returned as 7194 Fourth St. Task 4: Verify the updated candidate's address • • Select the statements from Task 2.14 Lab Instructions: Using XML Task 3: Update a candidate's address • Below the previous SELECT statement. you should have you have used XQuery with XML methods to view the selected contents of an XML schema and modified an XML object.Street)[1] with "7194 Fourth St.JobCandidateHistory SET Resume. Rockhampton. .com/sqlserver/2004/07/adventureworks/Resume' AS "RES") UPDATE HumanResources. and then verify that the desired results are returned. Execute the statements.

Use the following settings: • • • • Index name: PXML_Illustration_Diagram Index type: Clustered. nonunique Fill factor: Set the fill factor to 70 percent on leaf nodes Task 1: Create a new query file • Create a new query. They want to pilot the aspect of the schema used to describe illustrations of products in XML format. This will mean a dramatic increase in the use of the Production.sql . They hope to be able to provide XML-based illustrations of all products and to be able to retrieve data based on the property values of the XML data.Lab Instructions: Using XML 15 Exercise 4: Creating XML Indexes Scenario The Production department is also considering adopting the new industry standard XML schema to describe Adventure Works products. • File name: CreateXMLIndexes. nonunique Fill factor: Set the fill factor to 60 percent on both leaf and non-leaf nodes Secondary path index on the Diagram column.Illustration table and the amount of XML data stored there. You need to create the following indexes to accommodate the increased use: • Primary XML index on the Diagram column. Use these settings: • • • Index name: XMLPATH_Illustration_Diagram Index type: Nonclustered.

type the following code to create the primary XML index on the Diagram column of the Production. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. PAD_INDEX = ON) • In the query window.Illustration (Diagram) USING XML INDEX PXML_Illustration_Diagram FOR PATH WITH (FILLFACTOR = 70. Lab Shutdown After you complete the lab.Illustration table: CREATE XML INDEX XMLPATH_Illustration_Diagram ON Production. below the existing code. you have created XML indexes.16 Lab Instructions: Using XML Task 2: Create XML indexes • In the query window. .Illustration table: USE AdventureWorks2008 GO SET ARITHABORT ON CREATE PRIMARY XML INDEX PXML_Illustration_Diagram ON Production.Illustration (Diagram) WITH (FILLFACTOR = 60. Verify that the new XML indexes are listed and are correct. type the following code to create the secondary path XML index on the Diagram column of the Production. Results: After this exercise. PAD_INDEX = OFF) GO • • Execute the code and verify that the script completed without any errors.

Lab Instructions: Implementing Views 1 Module 6 Lab Instructions: Implementing Views Contents: Exercise 1: Creating Views Exercise 2: Creating Indexed Views Exercise 3: Creating Partitioned Views 2 6 7 .

Remember to use the SCHEMABINDING option when you create the view. . It was also found that indexed views and partitioned views will also improve performance.vEmployeeDetails that uses the following SELECT logic.2 Lab Instructions: Implementing Views Lab: Implementing Views Exercise 1: Creating Views Scenario Adventure Works finds that their database systems aren’t performing as well as they would like. The senior database developer has asked you to perform the following task: • Create a new view named HumanResources. After consultation with the Human Resources department. because you will need to create an index on the view later. The senior database developer has decided to start by creating views to simplify the analysis of employee details and contact information. the senior database developer has identified a number of views that will improve database performance and simplify future development.

File name: CreateEmployeeView. you must add a new view to SQL Server at the New York City location. Test the HumanResources.sql . Start the Server Management Studio and connect to the server.Lab Instructions: Implementing Views 3 In this exercise. 3. 3.vEmployeeDetails view. • Name: AW_Views Location: E:\Mod06\Labfiles\Starter Create a new query file. Create a SQL Server Scripts project.vEmployeeDetails view. • • 4. Create a new project. 2. Task 1: Create a SQL Server Scripts project 1. 2. The main tasks for this exercise are as follows: 1. Create the HumanResources. Start 6232A-NY-SQL-01 and logon as Student using the password Pa$$w0rd.

CountryRegionCode 2.a.e.StateProvince sp ON sp.FirstName .Person c ON c.Name AS CountryRegionName . 5.c.JobTitle .CountryRegion cr ON cr.c.a.sp.BusinessEntityID = e. Type the following Transact-SQL code to create the HumanResources.c.c.a.BusinessEntityAddress ea ON e.4 Lab Instructions: Implementing Views Task 2: Create the HumanResources.vEmployeeDetails WITH SCHEMABINDING AS SELECT e.CountryRegionCode = sp.c.City .LastName .c. Verify that the correct columns are listed in the view. . Verify that the HumanResources.cr.StateProvinceID INNER JOIN Person.Suffix .BusinessEntityID INNER JOIN Person.Name AS StateProvinceName .vEmployeeDetails view: USE AdventureWorks2008 GO CREATE VIEW HumanResources.AddressID = a. Examine this code. BusinessEntityID INNER JOIN Person. Examine the Messages box and verify that the script completed without any errors.AddressLine2 .AdditionalContactInfo FROM HumanResources. Execute the code.Title .c.AddressID INNER JOIN Person.StateProvinceID = a.a.vEmployeeDetails view is listed in the Object Explorer.Employee e INNER JOIN Person. 4.AddressLine1 .BusinessEntityID .Address a ON ea. 3.vEmployeeDetails view 1.MiddleName .PostalCode . BusinessEntityID = ea.EmailPromotion .

Results: After this exercise.sql In the blank query window. type the following code: Use AdventureWorks2008 SELECT * FROM HumanResources.Lab Instructions: Implementing Views 5 Task 3: Test the HumanResources. Examine the Messages box and verify that the script completed without any errors. 4.vEmployeeDetails view 1. Examine this code. File name: TestEmployeeView. Execute the code. 5. Create a new query file. . you should have created and tested of a new view for the database. • 2.vEmployeeDetails 3. Verify that correct data is returned from the view.

In this exercise.vEmployeeDetails view.6 Lab Instructions: Implementing Views Exercise 2: Creating Indexed Views Scenario After testing the HumanResources. you should have created a new view index. Examine this code. • File name: CreateViewIndex.vEmployeeDetails (BusinessEntityID) 2. type the following Transact-SQL code to create the IX_vEmployeeDetails index on the HumanResources. 4.vEmployeeDetails view into an indexed view by creating a unique clustered index named IX_vEmployeeDetails on the EmployeeID column. The main tasks for this exercise are as follows: 1. the senior database developer has asked you to perform the following task: • Turn the HumanResources. Execute the code. 2. 3.sql Task 2: Create the IX_vEmployeeDetails index 1. you need to create an indexed view for the SQL Server database.vEmployeeDetails view: USE AdventureWorks2008 GO CREATE UNIQUE CLUSTERED INDEX IX_vEmployeeDetails ON HumanResources. In the query window. Verify that the the IX_vEmployeeDetails index is listed in Object Explorer. . Examine the Messages box and verify that the script completed without any errors. Create a new query file. Create the IX_vEmployeeDetails index. Results: After this exercise. Task 1: Create a new query file • Create a new query file.

Lab Instructions: Implementing Views 7 Exercise 3: Creating Partitioned Views Scenario After testing the HumanResources.sql .Person. Create a new query file. Create the Person. • File name: CreatePartitionedView. 2.AW_Contacts.vContact distributed partitioned view. The main tasks for this exercise are as follows: 1.vContact on the AW_Contacts database. The view should union the sets of data contained in the following source servers and tables: • • • [NY-SQL-01]. the senior database developer has asked you to perform the following task: • Create a distributed partitioned view named Person.AW_Contacts. Prepare the SQL Server instances.cmd Task 2: Create a new query file • Create a new query file.Contact [NY-SQL-01 \SQLINSTANCE3].vEmployeeDetails view.AW_Contacts.Contact In this exercise.Person. Task 1: Prepare the SQL Server instances • Execute the following code: • E:\Mod06\Labfiles\Starter\ LabSetup.Person. 3.Contact [NY-SQL-01 \SQLINSTANCE2]. you need to configure the SQL Server databases and create a new partitioned view.

vContact AS SELECT * FROM [NY-SQL-01]. Execute the code. 9. In the query window.vContact view contains the data from the Person.AW_Contacts. Examine this code.AW_Contacts.vContact view: USE AW_Contacts GO SELECT * FROM Person. Examine this code. Results: After this exercise.Contact tables on all three SQL Server instances. 3. Verify that the correct columns are listed in the view.8 Lab Instructions: Implementing Views Task 3: Create the Person. type the following code to create the distributed partitioned view named Person.Person.vContact 8. 4. you should have configured and tested a new partitioned view for the SQL Server.vContact distributed partitioned view 1. • File name: ViewPersonContact.vContact on the AW_Contacts database: USE AW_Contacts GO CREATE VIEW Person. 5.AW_Contacts. .Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE3]. 6.Contact 2.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE2]. Execute the code. Examine Messages box and verify that the script completed without any errors. In the query window. type the following code to select the contents of the Person.vContact view is listed in the Object Explorer.Person. Verify that the result set of the Person.sql 7. Examine the Messages box and verify that the script completed without any errors. Create a new query file. Verify that the Person. 10.

. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.Lab Instructions: Implementing Views 9 Lab Shutdown After you complete the lab.

Lab Instructions: Implementing Stored Procedures 1 Module 7 Lab Instructions: Implementing Stored Procedures Contents: Exercise 1: Creating Stored Procedures Exercise 2: Working with Execution Plans 2 6 .

which is an nvarchar data type accepting up to 50 characters. and MaxQty. MinQty. in the E:\MOD07\Labfiles\Starter folder and has specified the following requirements for the modifications you must make: • Create a stored procedure named GetDiscounts within the Sales schema that retrieves the following columns from Sales.SpecialOffer: Description. DiscountPct. EndDate. Type.2 Lab Instructions: Implementing Stored Procedures Lab: Implementing Stored Procedures Exercise 1: Creating Stored Procedures Scenario The senior database developer has provided you with a SQL Server Scripts project named AWProgrammability. StartDate. but should filter the rows based on the @Category parameter. • . The procedure should retrieve the same columns as for GetDiscounts. Category. Create a stored procedure named GetDiscountsForCategory within the Sales schema that accepts an input parameter named @Category. The procedure should return all rows sorted by StartDate and EndDate.

The @DateToCheck parameter must be able to accept a NULL default value. Open the AWProgrammability. 4. • • • In this exercise.sql query file. and then execute it. but includes an additional @DateToCheck datetime input parameter. Create and test the GetDiscountsForCategoryAndDate stored procedure.GetDiscounts stored procedure according to the requirements. set the parameter value to the current date and time by using the GETDATE function. 2.Lab Instructions: Implementing Stored Procedures 3 • Create a stored procedure named GetDiscountsForCategoryAndDate within the Sales schema that accepts the @Category parameter as for GetDiscountsForCategory. 3. Always connect to the NY-SQL-01 SQL server when performing these tasks. you must use SQL Server Management Studio to open a SQL Scripts project and create the stored procedures specified within. . 3. Create and test the GetDiscounts stored procedure. Start 6232A-NY-SQL-01. and log on as Student with the password of Pa$$w0rd. 2.SpecialOffer table. Task 1: Create and test the GetDiscounts stored procedure 1. 4.ssmssln solution in the E:\MOD07\Labfiles\Starter folder. Create the stored procedure by executing the code under the --Create GetDiscount comment. but should filter the rows based on the @Category and @DateToCheck parameters. Open the InitilizeData. Create and test the AddDiscount stored procedure. and then execute your CREATE PROCEDURE statement. Test the stored procedure by executing the code under the – Test GetDiscounts comment. Create a stored procedure named AddDiscount within the Sales schema that inserts new records into the Sales. confirming that no errors occur. Create the Sales. confirming that no errors occur. Create and test the GetDiscountsForCategory stored procedure. If a NULL value is specified for the @DateToCheck parameter. The procedure should retrieve the same columns as for GetDiscounts. The main tasks for this exercise are as follows: 1.

Create the Sales. Test the Sales. Create the Sales.AddDiscount stored procedure by using the following parameter values: Parameter @Description @DiscountPct @Type @Category @StartDate @EndDate @MinQty @MaxQty Value 'Half price of everything' . 2. confirming that no errors occur. and then execute your CREATE PROCEDURE statement.GetDiscountForCategory stored procedure according to the requirements.GetDiscountsForCategoryAndDate stored procedure using 'Reseller' for the @Category value and the default value for the @DateToCheck parameter. Task 3: Create and test the GetDiscountsForCategoryAndDate stored procedure 1.AddDiscount stored procedure according to the requirements.GetDiscountsForCategory stored procedure using 'Reseller' for the @Category value. Create the Sales. and then execute your CREATE PROCEDURE statement. Review the results. Test the Sales. Task 4: Create and test the AddDiscount stored procedure 1.4 Lab Instructions: Implementing Stored Procedures Task 2: Create and test the GetDiscountsForCategory stored procedure 1. confirming that no errors occur.GetDiscountForCategoryAndDate stored procedure using 'Reseller' for the @Category value and a date one month from now for the @DateToCheck value. 3. Test the Sales. and then execute your CREATE PROCEDURE statement. confirming that no errors occur. Test the Sales. 2.5 'Seasonal Discount' 'Customer' Local variable with current date from GETDATE function Local variable with date one month from current date 0 20 2. . and then review the results.GetDiscountsForCategoryAndDate stored procedure according to the requirements. Review the results.

. you should have created and tested 4 stored procedures.ErrorLog table to confirm the error. and change the @DiscountPct value to -0.5.Lab Instructions: Implementing Stored Procedures 5 3. 4. Results: After this exercise. Use the return value from the stored procedure to determine whether the insert succeeded or failed. select the latest record from the dbo. Copy the previous test. If the insert failed. Confirm that a new special offer was create by displaying the @NewProductID OUTPUT parameter value.

6 Lab Instructions: Implementing Stored Procedures Exercise 2: Working with Execution Plans Scenario The senior database developer has identified some queries that may not be performing as well as they could be. 4.ssmssln project. students will view text-based execution plans. You must investigate the execution plans for the queries to identify problem areas. The main tasks for this exercise are as follows: 1. Task 1: View the text-based execution plan • • Select and execute the code between comments --Test the text-based execution plan and --Test the graphical execution plan. Observe the text-based execution plan in the results pane Task 2: View the graphical execution plan • • Select and execute the code below the comment --Test the graphical execution plan. 3. graphical execution plans.Product. View text-based execution plans. Tune the database to improve performance. Create an index on name.Name column using the TransactSQL below the comment --Tune the database. tune the database to improve performance and view revised execution plans. View graphical execution plans. These queries are provided for you in the ExecutionPlans. In this exercise. Observe the percentages of the execution plan involved in each operation Task 3: Tune the database to improve performance • Create an index on the Production. View the revised execution plans. 2. .sql query file in the AWProgrammability.

Results: After this exercise. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. . Lab Shutdown After you complete the lab. Observe the percentages involved in each operation of the query. you should have created and viewed both text-based and graphical execution plans.Lab Instructions: Implementing Stored Procedures 7 Task 4: View the revised execution plan • • Select and execute the code below the comment --retest the graphical execution plan.

Lab Instructions: Implementing Functions 1 Module 8 Lab Instructions: Implementing Functions Contents: Exercise 1: Creating Functions Exercise 2: Controlling Execution Context 2 8 .

2

Lab Instructions: Implementing Functions

Lab: Implementing Functions

Exercise 1: Creating Functions
Scenario
The senior database developer has provided you with a SQL Server Scripts project named AWProgrammability.ssmssln in the E:\MOD08\Labfiles\Starter folder and has specified the following requirements for the modifications you must make: • Create a scalar user-defined function named GetMaximumDiscountForCategory within the Sales schema that retrieves the maximum discount percentage currently available for a specific category. Create an @Category nvarchar(50) parameter to limit the results based on the category, and use the GETDATE function to limit the rows based on whether the discount is currently available.

Lab Instructions: Implementing Functions

3

Create an inline table-valued user-defined function named GetDiscountsForDate within the Sales schema that retrieves the same columns as the GetDiscounts stored procedure. The function accepts an @DateToCheck datetime parameter to filter the discounts based on the provided date. This allows Adventure Works to test what discounts will be available on a specific date. Create a multi-statement table-valued user-defined function named GetDiscountedProducts within the Sales schema that uses a complex query to retrieve products that have a discount. This complex query will be provided to you. The function accepts an @IncludeHistory bit parameter to filter the returned table based on whether the discount history information is required or only the current information is needed. Create a scalar user-defined function named GetCurrencyRate within the Sales schema that retrieves the latest currency conversion rate for a specific currency. The function accepts an @CurrencyCode nchar(3) parameter to specify the currency to return the conversion rate for. The currency data is located in the AdventureWorksDW2008 database and must be accessed by using the NY-SQL-01\Adam account. Create a multi-statement table-valued user-defined function named GetCurrencyDiscountedProducts within the Sales schema that is similar in functionality to the GetDiscountedProducts function but includes the price and discounted price in an alternate currency. The function accepts an @CurrencyCode nvarchar(3) parameter to specify the currency to be used.

In this exercise, you must use SQL Server Management Studio to open a SQL Scripts project and create the stored procedures specified within. The main tasks for this exercise are as follows: 1. 2. 3. Create and test the GetMaximumDiscountsForCategory user-defined function. Create and test the GetDiscountsForDate user-defined function. Create and test the GetDiscountedProducts user-defined function.

4

Lab Instructions: Implementing Functions

Task 1: Create and test the GetMaximumDiscountForCategory userdefined function
1. 2. 3. 4. 5. 6. 7. 8. 9. Start the NY-SQL-01 virtual machine. Logon as Administrator with the password: Pa$$w0rd. Run the createnewuser.vbs script located at E:\MOD08\Labfiles\Starter. Open Command Prompt. Browse to E:\MOD08\Labfiles\Starter. Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER. Log off Administrator and then logon as Student with the password: Pa$$w0rd. Open the SQL Server Management Studio scripts project located at E:\MOD08\Labfiles\Starter\AWProgrammability.ssmssln. In Solution Explorer open the query file InitilizeData.sql and execute its complete contents, ensure that it executes successfully. Connect to server NY-SQL-01 using Windows Authentication.

10. In Solution Explorer open the query file UserDefinedFunctions.sql. 11. Connect to server NY-SQL-01 using Windows Authentication. 12. Execute the Use AdventureWorks2008 statement. 13. Execute the CREATE FUNCTION statement as show in the example below:
CREATE FUNCTION Sales.GetMaximumDiscountForCategory (@Category nvarchar(50)) RETURNS smallmoney AS BEGIN DECLARE @Max smallmoney SELECT @Max = MAX(DiscountPct) FROM Sales.SpecialOffer WHERE Category = @Category AND GetDate() BETWEEN StartDate AND EndDate GROUP BY Category IF (@Max IS NULL) SET @Max = 0 RETURN @Max END

GetDiscountsForDate(GetDate()) ORDER BY DiscountPct DESC 5. MaxQty FROM Sales. DiscountPct.GetMaximumDiscountForCategory as shown in the example below: SELECT Sales. 4.sql query locate the Create Sales. Task 2: Create and test the GetDiscountsForDate user-defined function 1.GetDiscountsForDate comment. 2. . Type.Lab Instructions: Implementing Functions 5 14.GetMaximumDiscountForCategory('Reseller') 15. Verify that data is returned. Locate the Test Sales. Verify that a discount value is returned.GetDiscountsForDate comment. Category.SpecialOffer WHERE @DateToCheck BETWEEN StartDate AND EndDate ) 3. Execute the statement below the comment Test Sales. MinQty.GetDiscountsForDate (@DateToCheck datetime) RETURNS TABLE AS RETURN ( SELECT Description. Execute the CREATE FUNCTION statement as shown in the example below: CREATE FUNCTION Sales. StartDate. Test the function by executing the SELECT statement as show in the example below: SELECT * FROM Sales. In the UserDefinedFunctions. EndDate.

P.ProductID.SpecialOffer SO ON SOP.ProductID WHERE (SO. P.DiscountPct.Name.P.ListPrice. DiscountAmount money. P.GetDiscountedProducts comment.ListPrice * SO. SO. ListPrice money. Execute the CREATE FUNCTION statement as show in the example below. P.ListPrice * SO. DiscountedPrice money) AS BEGIN IF (@IncludeHistory = 1) INSERT @tbl_products SELECT P. In the UserDefinedFunctions. P.ListPrice .Description.Name. P.SpecialOfferID = SO.DiscountPct. SO.DiscountPct.ListPrice . CREATE FUNCTION Sales. P. DiscountDescription nvarchar(255). Name nvarchar(50).DiscountPct FROM Sales. SO.ProductID.P. 2. P.ListPrice * SO.ProductID = P.Description.SpecialOfferID INNER JOIN Production.DiscountPct .DiscountPct.ListPrice * SO.GetDiscountedProducts (@IncludeHistory bit) RETURNS @tbl_products TABLE (ProductID int.sql query locate the Create Sales.SpecialOfferProduct SOP INNER JOIN Sales.6 Lab Instructions: Implementing Functions Task 3: Create and test the GetDiscountedProducts user-defined function 1. DiscountPercentage smallmoney.Product P ON SOP. SO.DiscountPct > 0) ORDER BY ProductID ELSE INSERT @tbl_products SELECT P.ListPrice.

GetDiscountedProducts(1) 5.SpecialOfferProduct SOP INNER JOIN Sales.Lab Instructions: Implementing Functions 7 (continued) Sales. 4.SpecialOfferID = SO.Product P ON SOP. Locate the Test Sales. .DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END FROM 3.GetDiscountedProducts comment.GetDiscountedProducts(0) SELECT * FROM Sales.ProductID = P. Test the function by executing the SELECT statements as shown in the example below.SpecialOfferID INNER JOIN Production. Save UserDefinedFunctions.sql.ProductID WHERE (SO. you should have created and tested 3 user-defined functions.SpecialOffer SO ON SOP. SELECT * FROM Sales. Results: After this exercise.

You must establish a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008 databases to enable the GetCurrencyRate function to retrieve the currency data. 2. . The main tasks for this exercise are as follows: 1. Select and Execute the USE AdventureWorks2008 statement.GetCurrencyRate comment. In this exercise. you must use SQL Server Management Studio to open a SQL Scripts project and create the stored procedures specified within.sql. 3. Establish a database trust relationship between the AdventureWorks2008 database and the AdventureWorksDW2008 database. Connect to server NY-SQL-01 using Windows Authentication. The function accepts an @CurrencyCode nvarchar(3) parameter to specify the currency to be used. The function accepts an @CurrencyCode nchar(3) parameter to specify the currency to return the conversion rate for. Create a multi-statement table-valued user-defined function named GetCurrencyDiscountedProducts within the Sales schema that is similar in functionality to the GetDiscountedProducts function but includes the price and discounted price in an alternate currency. In Solution Explorer open the query file ExecutionContext. Create and test the GetCurrencyDiscountedProducts user-defined function. Task 1: Create the GetCurrencyRate user-defined function 1.8 Lab Instructions: Implementing Functions Exercise 2: Controlling Execution Context Scenario Create a scalar user-defined function named GetCurrencyRate within the Sales schema that retrieves the latest currency conversion rate for a specific currency. 2. 3. Create the GetCurrencyRate user-defined function. 4. The currency data is located in the AdventureWorksDW database and must be accessed by using the NY-SQL01\Adam account. Locate the Create Sales.

Lab Instructions: Implementing Functions

9

5.

Execute the CREATE FUNCTION statement as shown in the example below:

CREATE FUNCTION Sales.GetCurrencyRate (@CurrencyCode nchar(3)) RETURNS float WITH EXECUTE AS 'Adam' AS BEGIN DECLARE @CurrencyRate float SELECT @CurrencyRate = (SELECT TOP (1) EndOfDayRate FROM AdventureWorksDW2008.dbo.DimCurrency C INNER JOIN AdventureWorksDW2008.dbo.FactCurrencyRate CR ON C.CurrencyKey = CR.CurrencyKey WHERE C.CurrencyAlternateKey = @CurrencyCode ORDER BY CR.DateKey DESC) IF (@CurrencyRate IS NULL) SET @CurrencyRate = 1.0 RETURN @CurrencyRate END GO

6. 7.

Locate the Test Sales.GetCurrencyRate comment. Test the function by executing the SELECT statement as shown in the following example:

SELECT Sales.GetCurrencyRate('GBP')

Note: At this stage you have not established a trust relationship between the database, so you should expect to receive the following error message: The server principal "NY-SQL-01\Adam" is not able to access the database AdventureWorksDW2008 under the current security context.

8.

Save the ExecutionContext.sql query file.

Task 2: Establish a database trust relationship
1. 2. 3. In Solution Explorer open the TrustRelationship.sql query file. Execute the USE AdventureWorksDW2008 statement. Locate the Create the user for the NY-SQL-01\Adam login comment.

10

Lab Instructions: Implementing Functions

4.

Execute the CREATE USER statement as shown in the example below:

IF NOT EXISTS (SELECT * FROM sys.database_principals WHERE name = 'Adam' AND type = 'U') CREATE USER Adam FOR LOGIN [NY-SQL-01\Adam] GO

5. 6.

Locate the Grant Authenticate permission on the database comment. Execute the Transact-SQL code required to grant the mapped user AUTHENTICATE permission in the AdventureWorksDW2008 database as show in the example below:

GRANT AUTHENTICATE TO Adam GO

7. 8.

Locate the Grant SELECT permission to Adam comment. Execute the GRANT statement as show in the example below:

GRANT SELECT TO Adam GO

9.

Locate the Set the TRUSTWORTHY database option on the AdventureWorks2008 database comment.

10. Execute the ALTER DATABASE statement as show in the example below:
ALTER DATABASE AdventureWorks2008 SET TRUSTWORTHY ON GO

11. Verify that the statement executes successfully. 12. Save the TrustRelationship.sql query file.

Task 3: Create and test the GetCurrencyDiscountedProducts userdefined function
1. 2. 3. In Solution Explorer open the ExecutionContext.sql query file. Select and execute the USE AdventureWorks2008 statement. Locate the Test Sales.GetCurrencyDiscountedProducts comment.

Lab Instructions: Implementing Functions

11

4.

Execute the CREATE FUNCTION statement as show in the following example:

-- Sales.GetCurrencyDiscountedProducts CREATE FUNCTION Sales.GetCurrencyDiscountedProducts (@CurrencyCode nchar(3)) RETURNS @tbl_products TABLE (ProductID int, Name nvarchar(50), ListPrice money, CurrencyPrice money, DiscountDescription nvarchar(255), DiscountPercentage smallmoney, DiscountAmount money, DiscountedPrice money, DiscountedCurrencyPrice money) AS BEGIN DECLARE @CurrencyRate float SET @CurrencyRate = Sales.GetCurrencyRate(@CurrencyCode) INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, P.ListPrice * @CurrencyRate, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct, (P.ListPrice - P.ListPrice * SO.DiscountPct) * @CurrencyRate FROM Sales.SpecialOfferProduct SOP INNER JOIN Sales.SpecialOffer SO ON SOP.SpecialOfferID = SO.SpecialOfferID INNER JOIN Production.Product P ON SOP.ProductID = P.ProductID WHERE (SO.DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END GO

5. 6.

Verify that the statement executes successfully. Locate the Test Sales.GetCurrencydiscountedProducts comment.

. . Review the query results and verify that the statement executes successfully. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. Test the function by execution the SELECT statement as shown in the following example: SELECT * FROM Sales. you should have created two user-defined functions and created a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008. 9.12 Lab Instructions: Implementing Functions 7.GetCurrencyDiscountedProducts('GBP') 8. Save all open files and close Management Studio. Lab Shutdown After you complete the lab. Results: After this exercise.

Lab Instructions: Implementing Managed Code in a Database 1 Module 9 Lab Instructions: Implementing Managed Code in a Database Contents: Exercise 1: Importing an Assembly Exercise 2: Creating Managed Database Objects 2 4 .

The AWorksUtilities.dll managed assembly contains the following items: • • • • • A stored procedure named SaveXM A user-defined function named GetLongDate A trigger named EmailChange An aggregate named Concatenate A user-defined type named IPAddress .dll managed assembly is located in the E:\MOD09\Labfiles\Starter folder. and test the assembly. configure.dll.2 Lab Instructions: Implementing Managed Code in a Database Lab: Implementing Managed Code in a Database Exercise 1: Importing an Assembly Scenario The senior database developer has created the managed assembly named AWorksUtilities. you will only need to import. The AWorksUtilities.

. Execute the Initialize. 4.sql query file. 3. Open the ImportAssembly. Open the AWorks_CLR. and log on as Administrator with the password of Pa$$w0rd. 5. 2.sql query file. Import the AWorksUtilities assembly. Add and run the code to create the AWorksUtilities assembly. Results: After this exercise.Lab Instructions: Implementing Managed Code in a Database 3 In this exercise you will import the custom assembly: AWorksUtilities. The main tasks for this exercise are as follows: 1.sql query file and add and run the code to enable CLR Integration. Start the NY-SQL-01 virtual machine and log on as Administrator. Task 2: Import the AWorksUtilities assembly 1. Task 1: Start the NY-SQL-01 virtual machine and log on as Administrator • Start 6232A-NY-SQL-01. you should have the managed database objects in the AWorksUtilities assembly available for use within the AdventureWorks2008 database. 2.ssmssln solution. Save the changed ImportAssembly.

the senior database developer has requested that you create links to and test the new managed database objects. . • The SaveXML stored procedure should accept one xml parameter named @XmlData and one nvarchar(100) parameter named @FileName.SaveXML.IPAddress. The Concatenate aggregate accepts one nvarchar(4000) parameter named @input and returns an nvarchar(4000) value. The external name of the managed stored procedure is AWorksUtilities.GetLongDate.EmailAddress table. Create the EmailChange managed trigger on the Person. The GetLongDate user-defined function should accept one datetime parameter named @DateVal and should return an nvarchar(50) value. 2.4 Lab Instructions: Implementing Managed Code in a Database Exercise 2: Creating Managed Database Objects Scenario Now that you have imported the AWorksUtilities assembly for use in your company database. 3.EmailAddress table referencing the external assembly. The IPAddress user-defined type has the external name AWorksUtilities. The EmailChange trigger should fire only on updates to the Person.UserDefinedFunctions. The external name of the managed function is AWorksUtilities. • • • • In this exercise you will test each of the new managed database objects. Create the SaveXML managed stored procedure referencing the external assembly.StoredProcedures. The main tasks for this exercise are as follows: 1.Concatenate.EmailChange. The external name of the aggregate is AWorksUtilities. The external name of the trigger is AWorksUtilities.ssmssln in the E:\MOD09\Labfiles\Starter folder and the following requirements for the modifications you must make. Create the GetLongDate managed user-defined function referencing the external assembly. The senior database developer has provided you with a SQL Server Scripts solution named AWorks_CLR.Triggers.

2. Highlight and run the DECLARE. Task 1: Create the SaveXML managed stored procedure referencing the external assembly 1. Open the GetLongDate. and EXEC statements. 5. 5.sql file.sql query file and add the code to create the SaveXML stored procedure. 3. 6.Lab Instructions: Implementing Managed Code in a Database 5 4. Confirm that the records returned display with a long OrderDate value. Save the GetLongDate.sql query file.xml file and verify that the file contains XML.xml file in the E:\MOD09\Labfiles\Starter folder. 5. SET. 3. 2. 4. 4. Add the code to create the GetLongDate function then highlight and run the code. Add code to change the security permissions. Create the IPAddress managed user-defined type referencing the external assembly. Highlight and run the ALTER ASSEMBLY statement.sql file. 7. Task 2: Create the GetLongDate managed user-defined function referencing the external assembly 1. SET. Open the SaveXML. . Open the Output. Create the Concatenate managed aggregate function referencing the external assembly. Highlight and run the DECLARE. 9. Save the SaveXML. and EXEC statements. 8. Highlight and run the new code. Using Windows Explorer check for the existence of the Output. Select and run the SELECT statement and execute it.

Open the Concatenate.sql query file. 3. Task 5: Create the IPAddress managed user-defined type referencing the external assembly 1.sql file. 4. Task 4: Create the Concatenate managed aggregate function referencing the external assembly 1.sql file. you should have successfully imported assembly code and created managed database objects.6 Lab Instructions: Implementing Managed Code in a Database Task 3: Create the EmailChange managed trigger on the Person. 2. Add and execute the code to create the Concatenate aggregate.sql query file. 5. 5. 2. Save the EmailChange. Results: After this exercise. 4.sql query file. . 5.sql file. 2. 3. Save the IPAddress. Confirm that three result sets are displayed that show the IPAddress value in various forms. Open the IPAddress. Confirm that orders are displayed as a concatenated string. Highlight and execute the SELECT statement. 3. Add and execute the code to create the new IPAddress type Highlight and execute the SELECT statements.EmailAddress table referencing the external assembly 1. Open the EmailChange. 4. Add and execute the code to create the EmailChange trigger. Save the Concatenate. Highlight and execute the first UPDATE statement Highlight and execute the second UPDATE statement.

you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. .Lab Instructions: Implementing Managed Code in a Database 7 Lab Shutdown After you complete the lab.

Lab Instructions: Managing Transactions and Locks 1 Module 10 Lab Instructions: Managing Transactions and Locks Contents: Exercise 1: Using Transactions Exercise 2: Managing Locks 2 4 .

You will work with simple queries to ensure that you understand the issues before you implement this in the live database.2 Lab Instructions: Managing Transactions and Locks Lab: Managing Transactions and Locks Exercise 1: Using Transactions Scenario You are a database developer in the IT department of Adventure Works Bicycle manufacturing company. Task 1: Start the virtual machine and log on as Student 1. In order to avoid data integrity issues that are occurring. . next to 6231A-NY-SQL-01. 2. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. click Launch. you need to enclose some of your business logic in transactions. In the Lab Launcher.

5. 6. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Notice that the transaction has not ended. 8. Add a statement to roll back the transaction in the appropriate place. Open the script E:\Mod10\Labfiles\Starter\Tran1. Execute the last two statements of the script to verify that the changes have been committed to the database. Open the script E:\Mod10\Labfiles\Starter\Tran2. you should have committed and rolled back transactions. 3. . 5. Execute the script. Review the script.sql and connect to the NY-SQL-01 instance by using Windows authentication. 9. Add a statement to commit the transaction in the appropriate place. Results: After this exercise. Close SQL Server Management Studio.sql and connect to the NY-SQL-01 instance by using Windows authentication. 2. 2. Execute the statement that you have just added to end the transaction. 4. Add a statement to begin a transaction in the appropriate place. 7. 4. Review the script. Close the file.Lab Instructions: Managing Transactions and Locks 3 Task 2: Create and commit a transaction 1. 3. Task 3: Create and rollback a transaction 1. Execute the script and verify that the changes are not made and the transaction is complete.

8. execute a ROLLBACK TRANSACTION statement. 3.dm_tran_locks dynamic management view and note the new locks have been released. resource_type request_mode request_type request_status request_session_id Execute the query and review the results that show the lock on the master database. 7. . so you must test out some scenarios to identify and resolve the issues.sql and connect to the NY-SQL-01 instance by using Windows authentication.dm_tran_locks dynamic management view. 2. noting the SPID of your connection. • • • • • 4. Execute the query against the sys.dm_tran_locks dynamic management view and note the new locks listed. Use the Activity Monitor window to review the additional locks held.4 Lab Instructions: Managing Transactions and Locks Exercise 2: Managing Locks Scenario Now. Use the Activity Monitor window to review the current lock information. In the Lock1 query window. you also need to solve some locking errors that are occurring in user applications. 10. Review and execute the script. 5. Open the script E:\Mod10\Labfiles\Starter\Lock1. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Task 1: View locking information 1. 6. 9. Create a new query to select the following columns from the sys. Execute the query against the sys.

sql and connect to the NY-SQL01 instance by using Windows authentication.sql script and verify that the waiting transaction has been cancelled.sql script to change the lock timeout to five seconds. Review the contents of the file and execute the script. Lab Shutdown After you complete the lab. Open E:\Mod10\Labfiles\Starter\Lock1. 2. 4. Execute the query and note that the query now times out. 8. 7. Review the contents of the file and execute the script. you should have set locking options and set the lock timeout. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. Cancel the Lock2. Results: After this exercise. 3. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. 3. Task 3: Set the lock timeout 1.Lab Instructions: Managing Transactions and Locks 5 Task 2: Set locking options 1. Close SQL Server Management Studio. Execute the script and notice the WAIT entry in the request_status column. 6.sql and connect to the NY-SQL-01 instance by using Windows authentication.sql and connect to the NY-SQL-01 instance by using Windows authentication. 2. 5. . Open E:\Mod10\Labfiles\Starter\Lock2. Add a SET statement to the start of the Lock2. Open E:\Mod\10Labfiles\Starter\LockList.

Lab Instructions: Using Service Broker 1 Module 11 Lab Instructions: Using Service Broker Contents: Exercise 1: Creating Service Broker Objects Exercise 2: Implementing the Initiating Service Exercise 3: Implementing the Target Service 2 7 8 .

. the senior database developer has decided to implement this functionality through a service that will be invoked asynchronously when a new user registers.2 Lab Instructions: Using Service Broker Lab: Using Service Broker Exercise 1: Creating Service Broker Objects Scenario The Marketing department at Adventure Works wants to send a welcome e-mail message to new customers who register on the company’s Web site. You will create two Service Broker services: CustomerService will initiate a conversation with an EmailService. which will send an e-mail message to a newly registered customer. To minimize the impact to the site’s scalability.

CREATE TABLE EMailSvc. To enable secure communication between services.cmd to configure Database Mail on your development computer. The EmailLog table should have the following definition. CustomerData xml ) • • • Use the following details to create a message type that will be used to pass customer data to the EmailService service. [Event] nvarchar(50) NOT NULL. Property Name Message type Message Direction Value //AW/EMail/SendCustomerDetails //AW/EMail/CustomerDetails SENT BY INITIATOR . you must also create a master key with a secure password in the AdventureWorks database. and then create a table named EmailLog in the EmailSvc schema.Lab Instructions: Using Service Broker 3 When your work is complete. You must enable Service Broker in the AdventureWorks database by using the ALTER DATABASE statement. The database administrator has provided a batch file named LabSetup. the senior database developer will modify the customer registration process to use the services you create.EmailLog ( Date datetime NOT NULL. The senior database developer has provided the following specifications for the solution: • The EmailService service must be configured to send e-mail messages by using Database Mail. You must create schemas named EmailSvc and CustomerSvc in the AdventureWorks database. Property Name Validation Value //AW/EMail/CustomerDetails WELL_FORMED_XML • Use the following details to create a contract that will be supported by the EmailService service.

queue and services required for the solution. Create the AW_ServiceBroker SQL Server Scripts project.NewCustomerQueue ON • Use the following details to create a queue that will be used by the EmailService service.4 Lab Instructions: Using Service Broker • Use the following details to create a queue that will be used by the CustomerService service. enable Service Broker in the AdventureWorks2008 database. Property Name Queue status Value EMailSvc.NewCustomerEmailQueue OFF • Use the following details to create the CustomerService service.NewCustomerEmailQueue //AW/EMail/SendCustomerDetails In this exercise. Property Name Queue status Value CustomerSvc. The queue should initially be disabled until you create the stored procedure that the queue will activate. you will configure Database Mail. and then create the message type. 2. Launch SQL Server Management Studio. Property Name Queue Contract Value //AW/EMail/EmailService EMailSvc. . The main tasks for this exercise are as follows: 1. Property Name Queue Value //AW/Sales/CustomerService CustomerSvc. contract.NewCustomerQueue • Use the following details to create the EmailService service.

Open SQL Server Management Studio and connect to the default database engine.sql query you should create message types. Create a new project named AW_ServiceBroker in the E:\MOD11\Labfiles\Starter folder. and set the database to multi-user mode. create a schema named EMailSvc. Task 3: Configure the AdventureWorks database for Service Broker 1. Create a new query named PrepareDatabase. Configure the AdventureWorks database for Service Broker. Task 1: Launch SQL Server Management Studio • Launch 6232A-NY-SQL-01 and log on to NY-SQL-01 as Student using the password Pa$$w0rd. . create a table to log details of the customer e-mails sent. and create services based on the information provided in the scenario section of this exercise. Task 4: Create the Service Broker objects required for the customer email solution 1. Task 2: Create the AW_ServiceBroker SQL Server Scripts project 1. create another schema named CustomerSvc. 4.sql in the AdventureWorks2008 database. create a master key encryption with the password 23987hxJ#KL95234nl0zBe. create queues.sql query you should enable Service Broker. Create the Service Broker objects required for the customer e-mail solution. 2. Create a new query named CreateServiceBrokerObjects. In the CreateServiceBrokerObjects.Lab Instructions: Using Service Broker 5 3.sql in the AdventureWorks2008 database. 2. create contracts. 2. In the PrepareDatabase.

you should have configured the AdventureWorks database for Service Broker and then created the Service Broker objects required for the customer e-mail solution. In addition. you should have created the AW_ServiceBroker SQL Server Scripts project. .6 Lab Instructions: Using Service Broker Results: After this exercise.

Add the CreateEmailNewCustomerSP.sql query file in the E:\MOD11\Labfiles\Starter folder to the project. 2. Task 2: Implement the CustomerService service 1.Lab Instructions: Using Service Broker 7 Exercise 2: Implementing the Initiating Service Scenario Now you have to create a stored procedure that sends messages from the CustomerService service to the EmailService service. This code creates a stored procedure that sends messages from the CustomerService service to the EmailService service.uspEmailNewCustomer stored procedure used by the services. Execute the CreateEmailNewCustomerSP. you will add an existing query file to the project and execute the code in it. Implement the CustomerService service.sql query file to the AW_ServiceBroker project. In this exercise. Add the CreateEmailNewCustomerSP. . Results: After this exercise.sql query file to the AW_ServiceBroker project 1. you should have created the CustomerSvc. The senior database developer has provided Transact-SQL scripts to create the CustomerSvc.uspEmailNewCustomer stored procedure is listed under the Stored Procedures list of the AdventureWorks2008 database. 2.uspEmailNewCustomer stored procedure used by the service. The main tasks for this exercise are as follows: 1 2. Verify that the CustomerSvc.sql query. Task 1: Add the CreateEmailNewCustomerSP. Use the Add Existing Item option to add an item to the project.

you will add an existing query file to the project and execute the code it contains. 4.uspSendCustomerEmail 5 OWNER In this exercise. The senior database developer has provided TransactSQL scripts to create the EMailSvc. After you have created the EMailSvc. 2. Property Name Queue status Activation status Procedure name Maximum readers Execute as Value EMailSvc. Implement the EmailService service. .EMailSvc. The main tasks for this exercise are as follows: 1.uspSendCustomerEmail stored procedure whenever a message is received.uspSendCustomerEmail stored procedure used by the services. Test the EmailService service.sql query file to the AW_ServiceBroker project.8 Lab Instructions: Using Service Broker Exercise 3: Implementing the Target Service Scenario Now you have to create a stored procedure that receives and processes messages in the EmailService service. Use the following settings. you must alter the queue used by the EmailService service to make it activate the EMailSvc.uspSendCustomerEmail stored procedure. Add the CreateSendEmailSP. 3. This code creates a stored procedure that receives and processes messages in the EmailService service. Configure the target service for automatic activation.NewCustomerEmailQueue ON ON AdventureWorks.

uspSendCustomerEmail stored procedure is listed under the Stored Procedures list of the AdventureWorks2008 database. Verify that the EMailSvc. Execute the query.sql query file in the E:\MOD11\Labfiles\Starter folder to the project. Create a new query named AlterServiceBrokerQueue.Lab Instructions: Using Service Broker 9 Task 1: Add the CreateSendEmailSP.sql. 3. 2.sql query. Task 4: Test the EmailService service 1. Lab Shutdown After you complete the lab.NewCustomerEmailQueue queue activate the EMailSvc. Results: After this exercise. 2. In the query window. 3. 2. Use the Add Existing Item option to add an item to the project.sql query file in the E:\MOD11\Labfiles\Starter folder to the project. Add the CreateSendEmailSP. you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes. Execute the CreateSendEmailSP. Add the TestEmailService. Execute the query.sql query file to the AW_ServiceBroker project 1. Task 2: Implement the EmailService service 1. 2. Task 3: Configure the target service for automatic activation 1.uspSendCustomerEmail stored procedure using the settings provided in the scenario. you should have created a stored procedure that receives and processes messages in the EmailService service. You should have also tested the EmailService service. . Use the Add Existing Item option to add an item to the project. write a T-SQL statement to make the EMailSvc.

Lab Answer Key: Creating Databases and Database Files 1 Module 1 Lab Answer Key: Creating Databases and Database Files Contents: Exercise 1: Creating a Database Exercise 2: Creating a Schema Exercise 3: Creating a Database Snapshot 2 4 6 .

10. 13. Click Add. In the Lab Launcher. and then click New Database. 9. select Default. 12. enter AW_IT_Assets_Data2. 4. The New Database window appears. Maximize Microsoft SQL Server Management Studio.2 Lab Answer Key: Creating Databases and Database Files Lab: Creating Databases and Database Files Exercise 1: Creating a Database Task 1: Create a SQL Server Management Studio Scripts project 1. Click the cell labeled PRIMARY at the intersection of the AW_IT_Assets_Data2 row and the Filegroup column. enter AW_IT_Assets_Data1. Click Start | All Programs | Microsoft SQL Server 2008. 3. in the Database name field. 7. and then click Connect. Click the logical name cell of the new database file. A new database file is added to the Database files pane. click Launch. In Object Explorer expand NY-SQL-01. 6. Maximize the window. Enter 20 in the Initial Size column of the AW_IT_Assets_Data1 row. verify that Server type is set to Database Engine and Server name is set to NY-SQL-01. 8. and then select <new filegroup> from the drop-down menu. right-click Databases. and then click OK. On the General page. and then click SQL Server Management Studio. next to 6232A-NY-SQL-01. enter AW_IT_Assets. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Enter SECONDARY in the Name field. . In the Database files pane. and then press ENTER. In the Connect to Server dialog box. The New Filegroup for AW_IT_Assets dialog box appears. 14. and then press ENTER. click the AW_IT_Assets logical name. 5. 11. 2.

Click (…) in the Autogrowth column of the AW_IT_Assets_Data2 row and the Change Autogrowth for AW_IT_Assets_Data2 dialog box appears. Click (…) in the Path column of the AW_IT_Assets_log row and the Locate Folder windows appears. 24. Enter 20 in the Initial Size column of the AW_IT_Assets_Data2 row. and then click OK. enter AW_IT_Assets_DBScript in the File name field. Clear the Enable Autogrowth check box and then click OK. Click False in the Auto Shrink row of the Automatic options group and select True from the drop-down menu. 22. Enter 5 in the Initial Size column of the AW_IT_Assets_log row. 20. Click (…) in the Autogrowth column of the AW_IT_Assets_log row and the Change Autogrowth for AW_IT_Assets_log dialog box appears. In the Select a page pane of the New Database window. Click (…) in the Path column of the AW_IT_Assets_Data2 row and the Locate Folder windows appears.Lab Answer Key: Creating Databases and Database Files 3 15. and then click OK. and then click Save. 17. Click the down arrow next to Script at the top of the New Database window and select Script Action to File. select the Labfiles folder. 18. Click (…) in the Path column of the AW_IT_Assets_Data1 row and the Locate Folder windows appears. 25. click Options. and then click OK. 28. Expand E:\MOD01\. 34. 16. browse to E:\MOD01\Labfiles. 32. 30. select the Labfiles folder. In the Save As dialog box. 19. 31. 29. Expand E:\MOD01\. Click Cancel. 33. 27. Click False in the Auto Close row of the Automatic options group and select True from the drop-down menu. select the Labfiles folder. Clear the Enable Autogrowth check box and then click OK. 21. Clear the Enable Autogrowth check box and then click OK. 23. . Expand E:\MOD01\. Click (…) in the Autogrowth column of the AW_IT_Assets_Data1 row and the Change Autogrowth for AW_IT_Assets_Data1 dialog box appears. 26.

and then click Open. Browse to E:\MOD01\Labfiles. 2. click File.4 Lab Answer Key: Creating Databases and Database Files Task 2: Create a new database by executing a SQL Server Management Studio Scripts project 1. In SQL Server Management Studio expand NY-SQL-01 | Databases | AW_IT_Assets | Security. Click Execute on the SQL Editor toolbar. In Microsoft SQL Server Management Studio. 5. Once the status bar at the bottom of the query window displays “FileGroup Property ‘default’ has been set”. In the Database User New window. enter Katie in the User name field and NY-SQL-01\Katie in the Login name field. Note: The query may take several minutes to execute successfully. move on to step 4. select AW_IT_Assets_DBScript. 3. right-click Users. . 6. Expand NY-SQL-01 | Databases. The Open File dialog box appears. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise. 2. point to Open. Right-click NY-SQL-01 | Databases in Object Explorer and then click Refresh. The AW_IT_Assets database has been added to the Databases folder. and then click New User. and then click OK. 4. 7. you should have created a new database with the appropriate options and filegroups and created a SQL Server Management Studio Scripts project. and then click File. Exercise 2: Creating a Schema Task 1: Create a new database user 1. Results: After this exercise.

In the new. partnumber int) GRANT SELECT TO Katie. You should have also displayed ownership of the newly created schema. 5. type the following T-SQL statement: CREATE SCHEMA TechSupport AUTHORIZATION Katie CREATE TABLE Hardware (source int. Close the query editor without saving the query. click New Query. Click New Query on the Standard toolbar. Task 3: Create a schema and assign ownership to a user 1. On the toolbar.SCHEMATA WHERE SCHEMA_NAME = 'TechSupport'. Results: After this exercise.Lab Answer Key: Creating Databases and Database Files 5 Task 2: Create a schema and assign ownership to a user 1. GO 3. blank query window. cost int. click Execute. Keep Microsoft SQL Server Management Studio open for the next exercise. GO 3. Close the query editor without saving the query. click Execute. 2. type the following T-SQL statement: SELECT * FROM INFORMATION_SCHEMA. . In SQL Server Management Studio. 4. on the toolbar. 2. blank query window. In the new. On the toolbar. you should have created a schema and assigned ownership to a user. 4.

Click OK. 6. Task 2: Alter the database 1. click New Query. In SQL Server Management Studio. Expand NY-SQL-01 | Databases | AW_IT_Assets | Tables. blank query window. 4. Click OK. 3. right-click the TechSupport schema. and then click Delete. 5. In Object Explorer. right-click the TechSupport. Expand NY-SQL-01 | Databases | Database Snapshots and review the new database snapshot named AW_IT_Assets_Snapshot1.Hardware table. . ( NAME = AW_IT_Assets_Data2. 4. GO 3. and then click Refresh. The Delete Object window appears. and then click Delete.ss’ ) AS SNAPSHOT OF AW_IT_Assets.6 Lab Answer Key: Creating Databases and Database Files Exercise 3: Creating a Database Snapshot Task 1: Create a database snapshot 1. FILENAME = ‘E:\MOD01\Labfiles\Snapshots\AW_IT_Assets_Data2. On the toolbar.ss' ). 2. FILENAME = 'E:\MOD01\Labfiles\Snapshots\AW_IT_Assets_Data1. Close the query editor without saving the query. The Delete Object window appears. 2. right-click NY-SQL-01 | Databases. Expand NY-SQL-01 | Databases | AW_IT_Assets | Security | Schemas. type the following T-SQL statement: CREATE DATABASE AW_IT_Assets_Snapshot1 ON ( NAME = AW_IT_Assets_Data1. In the new. on the toolbar. click Execute.

and then click New Query.Lab Answer Key: Creating Databases and Database Files 7 Task 3: Revert the database to the previously created database snapshot 1. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes. On the toolbar. In the new. Expand NY-SQL-01 | Databases | AW_IT_Assets | Tables and NY-SQL-01 | Databases | AW_IT_Assets | Security | Schemas and note that both the TechSupport. and then reverted the database to the database snapshot. blank query window. RESTORE DATABASE AW_IT_Assets FROM DATABASE_SNAPSHOT = ‘AW_IT_Assets_Snapshot1'. . and then click Refresh. click Execute. expand NY-SQL-01 | Databases. 2. 4. you should have created a database snapshot. Right-click NY-SQL-01 | Databases.Hardware table and the TechSupport schema have been restored. In Object Explorer. right-click the AW_IT_Assets database. 5. altered the database. 6. Results: After this exercise. type the following T-SQL statement: USE master. GO 3.

Lab Answer Key: Creating Data Types and Tables 1 Module 2 Lab Answer Key: Creating Data Types and Tables Contents: Exercise 1: Creating Data Types Exercise 2: Using New Date and Time Data Types Exercise 3: Creating Tables Exercise 4: Creating Partitioned Tables 2 4 5 6 .

next to 6232A-NY-SQL-01. On the toolbar. click Refresh. 5. verify that Server type is set to Database Engine and Server name is set to NY-SQL-01. 10. 8. and then click SQL Server Management Studio. . Log on to NY-SQL-01 as Student using the password Pa$$w0rd. 2. Expand NY-SQL-01 | Databases. In the Connect to Server dialog box. In the new. and then click New Query. Close the query editor without saving the query. click Launch. click Execute. type the following T-SQL statement: CREATE TYPE ShortDescription FROM nvarchar(10) NOT NULL. 6.ShortDescription data type. blank query window. 7.2 Lab Answer Key: Creating Data Types and Tables Lab: Creating Data Types and Tables Exercise 1: Creating Data Types Task 1: Create a data types based on the nvarchar system-supplied data type 1. 9. 4. In the Lab Launcher. and then expand User-Defined Data Types to view the new dbo. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Programmability | Types | User-Defined Data Types. Click Start | All Programs | Microsoft SQL Server 2008. and then click Connect. Maximize Microsoft SQL Server Management Studio. 3. right-click the AdventureWorksDW2008 database.

click Refresh. and then expand User-Defined Data Types to view the new dbo. On the toolbar. type the following T-SQL statement: CREATE TYPE CashValue FROM decimal(8. 4. 5. click Execute. 2.Lab Answer Key: Creating Data Types and Tables 3 Task 2: Create a data type based on the decimal system-supplied data type 1.CashValue data type.2) NOT NULL. You should have also successfully created a new data type based on the decimal system-supplied data type. and then click New Query. 3. Close the query editor without saving the query. 6. Keep Microsoft SQL Server Management Studio open for the next exercise. blank query window. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Programmability | Types | User-Defined Data Types. . Results: After this exercise. In the new. you should have successfully created a new data type based on the nvarchar system-supplied data type. Right-click the AdventureWorksDW2008 database.

1234567 'time' .1234567 . 2.123' AS 'smalldatetime' .CAST('2007-05-08 12:35:29. Close the query editor without saving the query. CONVERT(time.1234567 'datetime2' . 126) AS UsingConvertTime.997' AS UnconvertedText.997'. Right-click the AdventureWorksDW2008 database.997' AS datetime) AS UsingCast. blank query window. ‘2006-04-04T15:50:59. CONVERT(date. 4. Right-click the AdventureWorksDW2008 database. In the new.4 Lab Answer Key: Creating Data Types and Tables Exercise 2: Using New Date and Time Data Types Task 1: Obtain date and time formatting using T-SQL 1. and then click New Query.CAST('2007-05-08 12:35:29. +12:15' AS time(7)) AS +12:15' AS date) AS 'date' smalldatetime) AS datetime) AS 'datetime' +12:15' AS datetime2(7)) AS +12:15' AS 3.CAST('2007-05-08 12:35:29.997'.1234567 datetimeoffset(7)) AS 'datetimeoffset'. GO .CAST('2007-05-08 12:35:29. CAST('2006-04-04T15:50:59. blank query window. In the new. On the toolbar. '2006-04-04T15:50:59. 126) AS UsingConvertDate. type the following T-SQL statement: SELECT '2006-04-04T15:50:59.123' AS . Task 2: Convert sample data into new data type formats using T-SQL 1. and then click New Query. click Execute and then review the results. 2.CAST('2007-05-08 12:35:29. type the following T-SQL statement: SELECT CAST('2007-05-08 12:35:29.

On the toolbar. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables. Amount CashValue ). ProductID int. Exercise 3: Creating Tables Task 1: Create a table named ReturnedGoods 1. On the toolbar. Results: After this exercise. 4. 2. click Execute. you should have successfully obtained date and time formatting using T-SQL and then converted sample data into the date and time formats using T-SQL. ReturnDate datetime.Lab Answer Key: Creating Data Types and Tables 5 3. 2. on the toolbar. click New Query. GO 3. Close the query editor without saving the query. ReturnReason ShortDescription NULL ). Right-click the AdventureWorksDW2008 database. and then click New Query. 5. In the new. click Execute and then review the results. blank query window. GO 3. and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new ReturnedGoods table. Keep Microsoft SQL Server Management Studio open for the next exercise. 5. type the following T-SQL statement: CREATE TABLE Refunds ( RefundID int identity. Close the query editor without saving the query. click Execute. 4. ReturnID int. click Refresh. . In the new. In SQL Server Management Studio. blank query window. Task 2: Create a table named Refunds 1. type the following T-SQL statement: CREATE TABLE ReturnedGoods ( ReturnID int identity. CustomerID int. On the toolbar.

click File. Browse to E:\MOD02\Labfiles\Scripts. Close the query editor without saving the query. click Refresh. and then click File. point to Open. and then click Open. click Execute. On the SQL Server Management Studio toolbar. 4. On the toolbar. and followed all provided specifications. and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new Refunds table. Results: After this exercise. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables. 6. select the file named partition_prep. created a table named Refunds. Keep Microsoft SQL Server Management Studio open for the next exercise. Close the query editor without saving the query. 5. .sql. you should have created a table named ReturnedGoods. Exercise 4: Creating Partitioned Tables Task 1: Limit result sets by using the INTERSECT clause with the SELECT statement 1. 3. 2.6 Lab Answer Key: Creating Data Types and Tables 4.

click Refresh. click New Query. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables. type the following T-SQL statement: CREATE PARTITION FUNCTION myRangePF1 (int) AS RANGE LEFT FOR VALUES (1. and Partitioning information in the right pane of the Table Properties window. 4. GO CREATE TABLE ReturnsArchive (ReturnID int identity. Test4FG). and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new ReturnsArchive table. click Execute. . Close the query editor without saving the query. In Object Explorer. 3. you should have successfully prepared the database for partitioning. right-click the dbo. and then click Refresh. 5. GO 3. right-click the AdventureWorksDW2008 database.Lab Answer Key: Creating Data Types and Tables 7 Task 2: Create a partitioned table named ReturnsArchive 1. On the toolbar. ProductID int. Results: After this exercise. In the Table Properties window. ReturnReason ShortDescription NULL ) ON myRangePS1 (ReturnID). on the toolbar. 100. GO CREATE PARTITION SCHEME myRangePS1 AS PARTITION myRangePF1 TO (Test1FG. Filegroups. Expand NY-SQL-01 | AdventureWorksDW2008 | Tables. Task 3: Review the partitioning implementation 1. click Storage on the left. 2. Test3FG.ReturnsArchive table. 5. ReturnDate datetime. CustomerID int. and then click OK. and then click Properties. In SQL Server Management Studio. created a partitioned table named ReturnsArchive according to the specifications provided. 1000). Test2FG. In the new. 2. Review the Compression. 4. blank query window. and then reviewed the partitioning changes.

Lab Answer Key: Creating and Tuning Indexes 1 Module 3 Lab Answer Key: Creating and Tuning Indexes Contents: Exercise 1: Creating Indexes Exercise 2: Optimizing Indexes 2 4 .

click Connect. next to 6232A-NY-SQL-01. Log on as Student with the password of Pa$$w0rd. 2. Task 2: Create a SQL Server Scripts project 1. . In the New Project dialog box. 5. In the Connect to Server dialog box. and then click SQL Server Management Studio. Clear the Create directory for solution check box. On the File menu. Click Start | All Programs | Microsoft SQL Server 2008. and then click OK. type AW_Indexes. 3. In the Lab Launcher. click New. Change the Location field to E:\MOD03\Labfiles\Starter.2 Lab Answer Key: Creating and Tuning Indexes Lab: Creating and Optimizing Indexes Exercise 1: Creating Indexes Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as Student 1. 2. in the Name field. click Launch. and then click Project. 4.

In Solution Explorer. Keep Microsoft SQL Server Management Studio open for the next exercise. expand Indexes. SafetyStockLevel) INCLUDE (DaysToManufacture) WITH (ALLOW_ROW_LOCKS = ON. In the query window. and then verify that the Ix_Product_Supply_Chain index is listed. expand Databases. you should have successfully created a SQL Server Scripts project and created the Ix_Product_Supply_Chain index. In Object Explorer. click Execute.Product (ProductNumber.sql. On the Project menu. click New Query. and then press ENTER. On the toolbar. type CreateIndex. 7. 9. If Object Explorer is not visible. on the View menu. .sql.Lab Answer Key: Creating and Tuning Indexes 3 Task 3: Create the Ix_Product_Supply_Chain index 1. click Save All. Color. Results: After this exercise.Product. Expand Production. 6. and then expand Tables. type the following Transact-SQL code to create the Ix_Product_Supply_Chain index: USE AdventureWorks2008 CREATE UNIQUE NONCLUSTERED INDEX Ix_Product_Supply_Chain ON Production. 8. On the File menu. ALLOW_PAGE_LOCKS = OFF. FILLFACTOR = 90. 2. PAD_INDEX = ON) 4. 5. 3. expand AdventureWorks2008. click Object Explorer. click Rename. ReorderPoint. right-click SQLQuery1.

Non-Clustered). browse to the E:\MOD03\Labfiles\Starter folder. 3. In the Index Properties – AK_Product_ProductNumber dialog box. Click Cancel. 2. notice that Total fragmentation has changed to 50. and then click Reorganize. in the Select a page pane. In Microsoft SQL Server Management Studio. in the Select a page pane. In the Open File dialog box. 2.00%. click OK. click Open. and then click File. notice that Total Fragmentation is 66. and then click Properties. Note that there may be some duplicate key errors.4 Lab Answer Key: Creating and Tuning Indexes Exercise 2: Optimizing Indexes Task 1: Add the sample products to the database 1. You can ignore this. In the Index Properties – AK_Product_ProductNumber dialog box. 3. 11. . 7. under Fragmentation. Task 2: Reorganize AK_Product_ProductNumber 1. In the details pane.Product | Indexes is still expanded. and then click Properties. 4. Right-click AK_Product_ProductNumber (Unique. and then click Open. Click Cancel. click Execute. 4. 6. click Fragmentation. 5. Wait for the query to finish executing before continuing to the next task. right-click AK_Product_ProductNumber (Unique. NonClustered). In the Reorganize Indexes dialog box. NonClustered). on the File menu. In Object Explorer. 10.67%. right-click AK_Product_ProductNumber (Unique. on the toolbar. In Object Explorer. 9. click Fragmentation.sql file. 8. In Object Explorer. In Microsoft SQL Server Management Studio. In the details pane. click the aw2008sampleproductadd. make sure that Databases | AdventureWorks2008 | Tables | Production.

notice that Total fragmentation is now 25. in the Select a page pane. In the details pane. and then click Rebuild. In Object Explorer. 7. 5.Product table indexes using both reorganize and rebuild. right-click AK_Product_Name (Unique. In the details pane. Click Cancel. you should have successfully optimized the Production.Lab Answer Key: Creating and Tuning Indexes 5 Task 3: Rebuild AK_Product_Name 1. 10. In the Index Properties – AK_Product_Name dialog box. In Object Explorer. click OK. 9. notice that Total fragmentation is 80. In the Index Properties – AK_Product_Name dialog box. .00%. click Fragmentation. Non-Clustered). and then click Properties. 6. In the Rebuild Indexes dialog box. Non-Clustered).00%. in the Select a page pane. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab. Non-Clustered). 2. 4. right-click AK_Product_Name (Unique. right-click AK_Product_Name (Unique. 8. Results: After this exercise. click Fragmentation. 3. In Object Explorer. and then click Properties.

Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers 1 Module 4 Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers Contents: Exercise 1: Creating Constraints Exercise 2: Disabling Constraints Exercise 3: Creating Triggers 2 4 6 .

On the File menu. click New. click Connect. In the Lab Launcher. 2. 3. Task 2: Create a SQL Server Scripts project 1. type AW_DataIntegrity. 5. Log on as Student with the password of Pa$$w0rd. . In the Connect to Server dialog box. in the Name field. and then click OK. and then click SQL Server Management Studio. Click Start | All Programs | Microsoft SQL Server 2008. Change the Location field to E:\MOD04\Labfiles\Starter. 4. Clear the Create directory for solution check box. In the New Project dialog box. and then click Project. next to 6232A-NY-SQL-01. 2.2 Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers Lab: Implementing Data Integrity by Using Constraints Exercise 1: Creating Constraints Task 1: Start the 6232A-NY-SQL-01 virtual machine and log on as Student 1. click Launch.

9. [BusinessEntityID] [int] NULL. .[JobCandidateHistory]( [JobCandidateID] [int] NOT NULL UNIQUE. On the Project menu. 7. 6. expand the Columns. [RejectedDate] [datetime] NOT NULL. and then verify that the HumanResources. and then click Refresh to see the new table.[BusinessEntity] (BusinessEntityID). and then verify that the necessary constraints have been implemented. 8. click Rename.sql. In the query window. Keys. expand Tables. On the File menu.Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers 3 Task 3: Create the JobCandidateHistory table and constraints 1.JobCandidateHistory table is listed. expand Databases. on the View menu. right-click SQLQuery1. click New Query. If Object Explorer is not visible. [Rating] [int] NOT NULL CONSTRAINT [DF_JobCandidateHistory_Rating] Default (5). type the following Transact-SQL code to create the JobCandidateHistory table: USE [AdventureWorks2008] GO CREATE TABLE [HumanResources]. and then press ENTER.JobCandidateHistory table. Indexes. In Solution Explorer. 3. expand AdventureWorks2008. In Object Explorer. expand the HumanResources. In Object Explorer.JobCandidateHistory table. CONSTRAINT [CK_JobCandidateHistory_Rating] CHECK ([Rating]>=0 AND [Rating]<=10) ) ON [PRIMARY] 4. type TableAndContraints. 2. click Object Explorer. click Save All. CONSTRAINT [FK_JobCandidateHistory_BusinessEntity_BusinessEntityID] FOREIGN KEY (BusinessEntityID) REFERENCES [Person]. 5. and Constraints folders.sql. You may need to rightclick Tables. click Execute. In the HumanResources. On the toolbar.

JobCandidateHistory table. 2. click TestConstraints. and then click Open. because the Rating value conflicts with the CHECK constraint. 4. select the code. on the File menu.sql. and then click Execute. on the File menu. right-click SQLQuery1. In Solution Explorer. and then on the toolbar. browse to the E:\MOD04\Labfiles\Starter folder. click Open. click New Query. In the Open File dialog box. . created the HumanResources. 4. and tested the constraints. click the Include Client Statistics button. click Rename. and verify that the Time Statistics have been recorded. 2.sql file. click Open. 3. 2. type Constraints. you should have successfully created a SQL Server Scripts project. Click the Client Statistics tab. In the Open File dialog box. browse to E:\MOD04\Labfiles\Starter. On the Project menu. and then press ENTER.4 Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers Task 4: Test the JobCandidateHistory table and constraints 1. click Execute. Below the comment This should succeed. Task 2: Disable constraints on the JobCandidateHistory table 1. Below the comment This should fail. select the code. 3. and then click File. 5. Results: After this exercise. and then click Open. Exercise 2: Disabling Constraints Task 1: Insert multiple rows into the JobCandidateHistory table 1. On the toolbar. In SQL Server Management Studio. and then on the toolbar. click Execute. and then click File. The INSERT operation should succeed. The INSERT operation should fail. Keep SQL Server Management Studio open to use in the next exercise. In Microsoft SQL Server Management Studio.sql.sql. click the InsertTestData.

Switch to the Constraints. Results: After this exercise.Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers 5 3. 6. 8. 9.sql query window. and then compare the Time Statistics with the previous trial. Verify that the commands completed successfully. Switch to the InsertTestData. 2. 7. On the File menu. Task 3: Enable constraints on the JobCandidateHistory table 1. On the File menu. 5. click Execute.JobCandidateHistory CHECK CONSTRAINT [CK_JobCandidateHistory_Rating] GO 3. click Execute. click Save All. click Save All. Verify that the commands completed successfully. Keep SQL Server Management Studio open for the next exercise. you should have successfully compared performance results with constraints enabled and disabled. type the following Transact-SQL code: USE [AdventureWorks2008] GO ALTER TABLE HumanResources. On the toolbar. 5. In the query window. click Execute. Click the Client Statistics tab. In the query window. and then on the toolbar.JobCandidateHistory NOCHECK CONSTRAINT [CK_JobCandidateHistory_Rating] GO 4. Select the new statements. Notice that Trial 2 executes more quickly. type the following Transact-SQL code below the existing statements: ALTER TABLE HumanResources. 6. . 4.sql query window. On the toolbar.

In the query window. 2.sql. On the toolbar. on the Project menu. On the File menu. click Execute. Expand the HumanResources. INSERT INTO [HumanResources]. .6 Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers Exercise 3: Creating Triggers Task 1: Create the dJobCandidate trigger 1. 4. getdate() FROM deleted END. type the following Transact-SQL code to create the dJobCandidate trigger on the HumanResources. RejectedDate) SELECT JobCandidateID. click New Query. and then press ENTER. 5. type Trigger. and then click Refresh. 7. 6.[JobCandidate] AFTER DELETE AS BEGIN SET NOCOUNT ON. Right-click Tables. In SQL Server Management Studio. click Save All. click Rename. and then verify that the dJobCandidate trigger is listed. expand Databases. expand Triggers.[JobCandidateHistory] (JobCandidateID.JobCandidate table: USE AdventureWorks2008 GO CREATE TRIGGER [dJobCandidate] ON [HumanResources]. In Solution Explorer.sql. expand AdventureWorks2008.JobCandidate table. 3. In Object Explorer. and then expand Tables. right-click SQLQuery1.

sql query file. 5. 2. browse to the E:\MOD04\Labfiles\Starter folder. On the File menu. In the Open File dialog box. The record should contain the default value of 5 for Rating. and then click Open. .JobCandidate table is inserted into the HumanResources. Results: After this exercise. 4. click Open. and the current date for RejectedDate. Close SQL Server Management Studio. and then click File. 6. 3. Click the Messages tab. In the results pane. On the toolbar. you should have successfully created and tested the dJobCandidate trigger. and then verify that there are two (1 row(s) affected) messages indicating that a row was deleted from one table and inserted into another. click Execute to execute the query script. verify that the record deleted from the HumanResources. and then shutdown the virtual machine without saving changes to reset it for the next Lab.JobCandidateHistory table. click the TestTrigger.Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers 7 Task 2: Test the dJobCandidate trigger 1.

Lab Answer Key: Using XML 1 Module 5 Lab Answer Key: Using XML Contents: Lab 5A: Using XML Exercise 1: Mapping Relational Data and XML Exercise 2: Storing XML Natively in the Database Lab 5B: Using XML Exercise 3: Using XQuery with XML Methods Exercise 4: Creating XML Indexes 16 18 2 6 .

point to Open. The Open Project dialog box appears. If Solution Explorer is not visible. 10. b. double-click the FORXML. On the toolbar. 6. on the View menu. click Solution Explorer. in the Solution Explorer pane. Switch to the FORXML query. In the Lab Launcher. click Connect. click Execute. next to 6232A-NY-SQL-01. If necessary. 2. Browse to the E:\Mod05\Labfiles\Starter folder. and then click Project/Solution. and then click Open. expand XML | Queries. Examine the query and note that it retrieves data from the Sales.ssmssln solution. On the File menu. Examine the Results and Messages boxes and verify that the script completed without any errors. 4. c. If the Connect to Server dialog box appears. Log on to NY-SQL-01 as Student using the password Pa$$w0rd.2 Lab Answer Key: Using XML Lab: Using XML Exercise 1: Mapping Relational Data and XML Task 1: Create the FOR XML queries to return the order manifest documents 1. 3.sql query to open it. 5. a. click Connect. In the Solution Explorer. . 9. click Launch. If the Connect to Server dialog box appears.SalesOrderDetail tables in the AdventureWorks2008 database. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio.SalesOrderHeader and Sales. 7. click the XML. 11. 8.

Modify the SELECT statement to include the FOR XML clause and return attribute-centric XML by using AUTO mode. SalesOrder. SalesOrder. click Execute. 15.SalesOrderID.OrderQty FROM Sales. Item. as shown in the following Transact-SQL example: SELECT SalesOrder.more items here --> </SalesOrder> 18.SalesOrderID = 43659 FOR XML AUTO 13. 17.SalesOrderID WHERE SalesOrder.ProductID.Lab Answer Key: Using XML 3 12.AccountNumber. On the toolbar. click Close to close the XML editor. In the query results.SalesOrderHeader SalesOrder JOIN Sales. . 14. Examine the Results and Messages boxes and verify that the script completed without any errors.OrderDate. 16. click the returned XML to view it in the XML editor.SalesOrderDetail Item ON SalesOrder. Item. On the File menu. It should be similar to the example shown in the following output: <SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item ProductID="776" OrderQty="1" /> <Item ProductID="777" OrderQty="3" /> <Item ProductID="778" OrderQty="1" /> <Item ProductID="771" OrderQty="1" /> <!-.SalesOrderID = Item. Review the query results.

4

Lab Answer Key: Using XML

19. Modify the SELECT statement, as shown in the following Transact-SQL example:
SELECT SalesOrder.SalesOrderID, SalesOrder.OrderDate, SalesOrder.AccountNumber, (SELECT Item.ProductID, Item.OrderQty FROM Sales.SalesOrderDetail Item WHERE SalesOrder.SalesOrderID = Item.SalesOrderID FOR XML AUTO, ELEMENTS, TYPE) FROM Sales.SalesOrderHeader SalesOrder WHERE SalesOrder.SalesOrderID = 43659 FOR XML AUTO

20. On the toolbar, click Execute. 21. Examine the Results and Messages boxes and verify that the script completed without any errors. 22. In the query results, click the returned XML to view it in the XML editor. 23. Verify that the query returned the required XML format, as shown in the following sample output:
<SalesOrder SalesOrderID="43659" OrderDate="2001-07-01T00:00:00" AccountNumber="10-4020-000676"> <Item> <ProductID>776</ProductID> <OrderQty>1</OrderQty> </Item> <Item> <ProductID>777</ProductID> <OrderQty>3</OrderQty> </Item> <Item> <ProductID>778</ProductID> <OrderQty>1</OrderQty> </Item> <!-- more items here --> </SalesOrder>

24. On the File menu, click Close to close the XML editor. 25. On the File menu, click Save FORXML.sql. 26. Keep the SQL Server Management Studio solution open. You will use it in the next part of this exercise.

Lab Answer Key: Using XML

5

Task 2: Use the OPENXML function to insert the XML data into the tables
1. 2. In the Solution Explorer pane, double-click the OPENXML.sql query to open it. Examine the query and note that it provides a sample XML document that contains a sales order from a customer for two items. The remainder of the file is incomplete. Locate the comment Call stored procedure to create the memory tree, and then add a call to the sp_xml_preparedocument stored procedure, as shown in the following example:
EXEC sp_xml_preparedocument @docHandle OUTPUT, @doc

3.

4.

Locate the comment Add OPENXML function for SalesOrderHeader table INSERT, and then add an OPENXML function to retrieve the relevant attributes from the SalesOrder node, as shown in the following example:
OPENXML(@docHandle, '/SalesOrder', 1) WITH ( CustomerID int, OrderDate datetime, DueDate datetime, AccountNumber nvarchar(15), SalesPersonID int, BillToAddressID int, ShipToAddressID int, ShipMethodID int, SubTotal money, TaxAmt money)

5.

Locate the comment Add OPENXML function for SalesOrderDetail table INSERT, and then add an OPENXML function to retrieve the relevant subelements from the Item node, as shown in the following example:
OPENXML(@docHandle, '/SalesOrder/Item', 2) WITH ( OrderQty int, ProductID int, UnitPrice money)

6

Lab Answer Key: Using XML

6.

Locate the comment Call stored procedure to clean up memory tree, and then add a call to the sp_xml_removedocument stored procedure, as shown in the following example:
EXEC sp_xml_removedocument @docHandle

7. 8. 9.

On the toolbar, click Execute. Examine the Results and Messages boxes and verify that the script completed without any errors. Review the results, and confirm that a new record was added to the SalesOrderHeader table and two records were added to the SalesOrderDetail table.

10. On the File menu, click Save All. 11. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you should have modified the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML.

Exercise 2: Storing XML Natively in the Database
Task 1: Create a SQL Server Scripts project in SQL Server Management Studio
1. 2. 3. 4. 5. 6. 7. On the File menu, point to New, and then click Project. The New Project dialog box appears. In the Templates box, makes sure SQL Server Scripts is highlighted. In the Name field, type Job Candidate History. In the Location field, type E:\Mod05\Labfiles\Starter. Click OK. In the Solution Explorer, right-click Connections, and then click New Connection. The Connect to Server dialog box appears. Click OK.

BusinessEntityID int NULL. . On the File menu. type the following Transact-SQL code to create a table named HumanResources. 7. 5. 9.JobCandidateHistory table 1.sql.sql As. click Connect. 11.JobCandidateHistory ( JobCandidateID int IDENTITY PRIMARY KEY. In the HumanResources. 10. In the Solution Explorer. 6. In Object Explorer. Verify that the HumanResources. If the Connect to Server dialog box appears. 2. Examine Messages box and verify that the script completed without any errors. click Connect. click Save SQLQuery1. On the toolbar. expand Databases | AdventureWorks2008 | Tables. The Save File As dialog box appears.JobCandidateHistory table. RejectedDate datetime NOT NULL.JobCandidateHistory in the AdventureWorks2008 database: USE AdventureWorks2008 GO CREATE TABLE HumanResources. click Execute. ModifiedDate DateTime. 3.Lab Answer Key: Using XML 7 Task 2: Create the HumanResources.JobCandidateHistory table.JobCandidateHistory table is listed. expand the HumanResources. If the Connect to Server dialog box appears. Rating int NOT NULL Default (5). and then click Save. right-click Queries. In the query pane. Verify that the necessary columns have been successfully created. expand Columns. 12. In Object Explorer. 8. NationalIDNumber nvarchar (15) NOT NULL. 13. type CreateJobCandidateHistoryTable. Resume xml ) GO 4. and then click New Query. In the File name field.

click SQL Server files. The Save File As dialog box appears. click Save SQLQuery2. On the File menu. . and then click Save. type XMLSchema. In the Solution Explorer. In the Solution Explorer. point to Add. click Connect.8 Lab Answer Key: Using XML Task 3: Create a new query file 1. and then click Existing item. In the Solution Explorer. 9.xml. If the Connect to Server dialog box appears. point to Add.Job Candidate History dialog box appears. 6. right-click Job Candidate History. click XML Files.sql As. Navigate to the E:\Mod05\Labfiles\Starter folder. 3. 2.sql.sql. In the File of type list. right-click Job Candidate History. 5. In the File name field. and then click Existing item. 2. Task 4: Create an XML schema collection named HumanResources. right-click Queries. 7. and then click Add. If the Connect to Server dialog box appears. 10. 8.Job Candidate History dialog box appears. 4. 3. Click CreateXMLSchema. Navigate to the E:\Mod05\Labfiles\Starter folder. click Connect. and then click New Query. and then click Add. In the File of type list. In the details pane. The Add Existing Item . 4. Click HistoricResumeSchema. examine the new schema definition.HistoricResumeSchemaCollection 1. The Add Existing Item .

org/2001/XMLSchema" xmlns:t="http://schemas.Location"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Location" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> <xsd:element name="Addr. It should be identical to the code listed below: USE AdventureWorks2008 GO CREATE XML SCHEMA COLLECTION HumanResources.microsoft.Type" type="xsd:string" /> <xsd:element name="Addr.com/sqlserver/2004/07/adv enture-works/Resume" elementFormDefault="qualified"> <xsd:element name="Address" type="t:AddressType" /> <xsd:element name="Education" type="t:EducationType" /> <xsd:element name="Employment" type="t:EmploymentType" /> <xsd:element name="Location" type="t:LocationType" /> <xsd:element name="Name" type="t:NameType" /> <xsd:element name="Resume" type="t:ResumeType" /> <xsd:element name="Telephone" type="t:TelephoneType" /> <xsd:complexType name="AddressType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Addr.Street" type="xsd:string" maxOccurs="unbounded" /> <xsd:element name="Addr.microsoft.HistoricResumeSchemaCollection AS N'<xsd:schema xmlns:xsd="http://www.Telephone" minOccurs="0"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> .PostalCode" type="xsd:string" /> <xsd:element name="Addr.Lab Answer Key: Using XML 9 11. Examine the code that creates the new XML Schema.w3.OrgName" type="xsd:string" /> <xsd:element name="Addr.com/sqlserver/2004/07/adventureworks/Resume" targetNamespace="http://schemas.

GPA" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.GPAAlternate" type="xsd:decimal" minOccurs="0" /> <xsd:element name="Edu.Location" minOccurs="0"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Location" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> .Minor" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.StartDate" type="xsd:date" /> <xsd:element name="Edu.School" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.Major" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.GPAScale" type="xsd:decimal" minOccurs="0" /> <xsd:element name="Edu.EndDate" type="xsd:date" /> <xsd:element name="Edu.Degree" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.10 Lab Answer Key: Using XML (continued) <xsd:element ref="t:Telephone" maxOccurs="unbounded" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="EducationType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Edu.Level" type="xsd:string" /> <xsd:element name="Edu.

CountryRegion" type="xsd:string" /> <xsd:element name="Loc.City" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> .State" type="xsd:string" minOccurs="0" /> <xsd:element name="Loc.FunctionCategory" type="xsd:string" minOccurs="0" /> <xsd:element name="Emp.Lab Answer Key: Using XML 11 (continued) <xsd:complexType name="EmploymentType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Emp.EndDate" type="xsd:date" minOccurs="0" /> <xsd:element name="Emp.IndustryCategory" type="xsd:string" minOccurs="0" /> <xsd:element name="Emp.StartDate" type="xsd:date" minOccurs="0" /> <xsd:element name="Emp.Responsibility" type="xsd:string" /> <xsd:element name="Emp.JobTitle" type="xsd:string" /> <xsd:element name="Emp.Location" minOccurs="0"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Location" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:element> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="LocationType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Loc.OrgName" type="xsd:string" /> <xsd:element name="Emp.

Suffix" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="ResumeType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element ref="t:Name" /> <xsd:element name="Skills" type="xsd:string" minOccurs="0" /> <xsd:element ref="t:Employment" maxOccurs="unbounded" /> <xsd:element ref="t:Education" maxOccurs="unbounded" /> <xsd:element ref="t:Address" maxOccurs="unbounded" /> <xsd:element ref="t:Telephone" minOccurs="0" /> <xsd:element name="EMail" type="xsd:string" minOccurs="0" /> <xsd:element name="WebSite" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> <xsd:complexType name="TelephoneType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Tel.Type" type="xsd:anyType" minOccurs="0" /> <xsd:element name="Tel.Middle" type="xsd:string" minOccurs="0" /> <xsd:element name="Name.IntlCode" type="xsd:int" minOccurs="0" /> <xsd:element name="Tel.Last" type="xsd:string" /> <xsd:element name="Name.12 Lab Answer Key: Using XML (continued) <xsd:complexType name="NameType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Name.AreaCode" type="xsd:int" minOccurs="0" /> <xsd:element name="Tel.First" type="xsd:string" /> <xsd:element name="Name.Number" type="xsd:string" /> .Prefix" type="xsd:string" minOccurs="0" /> <xsd:element name="Name.

Examine Messages box and verify that the script completed without any errors. If the Connect to Server dialog box appears. In the File name field. 9. 7. and then click Refresh.sql. click Execute. In the Solution Explorer. click Execute. ensure that Databases | AdventureWorks2008 are expanded.sql As. and then click New Query. 3. type AlterCandidateTable.Lab Answer Key: Using XML 13 (continued) <xsd:element name="Tel. and then click Save. On the toolbar. On the File menu. Examine Messages box and verify that the script completed without any errors. On the toolbar.JobCandidateHistory ALTER COLUMN Resume xml (HumanResources. click Save SQLQuery3. In Object Explorer. right-click Queries. In the query window. right-click AdventureWorks2008. 13. The Save File As dialog box appears.Resume column 1. 5. Task 5: Apply the schema collection to the JobCandidateHistory. enter the following code to alter the JobCandidateHistory table: ALTER TABLE HumanResources.JobCandidateHistory. In Object Explorer. 4. 8.Extension" type="xsd:int" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:schema>' GO 12. click Connect. expand Tables. and then expand Columns.HistoricResumeSchemaCollection) GO 6. . 2. expand HumanResources.

Notice that the Resume column is now associated with the HumanResources. .HistoricResumeSchemaCollection.14 Lab Answer Key: Using XML 10.

8. 3. 7. The INSERT operation should succeed. 13. right-click Queries. and then click Save. 14.Job Candidate History dialog box appears. The INSERT operation fails because the Resume XML does not conform to the schema. and then click Add. click Save SQLQuery4. On the toolbar. 9. Click TestXMLSchema. Examine the error message in the Messages pane. 12. If the Connect to Server dialog box appears. If the Connect to Server dialog box appears. 2.Lab Answer Key: Using XML 15 Task 6: Test the HistoricResumeSchema XML schema 1. 15. select the INSERT code. and then click Existing item. In the Solution Explorer pane. ensure that SQL Server files is selected. Below the comment This should succeed. On the File menu. . click Connect.sql. click Execute. In the details pane. click Connect. click Execute. The Add Existing Item . 11.sql As.sql. 10. In the File of type list. Navigate to the E:\Mod05\Labfiles\Starter folder. 6. right-click Job Candidate History. 4. In the File name field. type SelectCandidates. On the toolbar. and then click New Query. point to Add. Examine the Message box and verify that the script completed without any errors. 5. below the comment This should fail. select the code. The Save File As dialog box appears. In the Solution Explorer.

Examine the Results and Messages boxes and verify that the script completed without any errors. 21. 19. 18. On the toolbar. On the File menu. 5. Examine the Results and Messages boxes and verify that the script completed without any errors. If the Connect to Server dialog box appears. 12. 2. click Close to close the XML editor. On the toolbar. 9. In the Results pane.Job Candidate History dialog box appears.JobCandidateHistory table with additional sample data 1. click Close to close the XML editor.JobCandidateHistory GO 17. Examine the xml record to confirm that it is accurate. 4. In the Results pane. and then click Add. 8. click the <Resume> field. In the Solution Explorer. In the File of type list. click Execute. Task 7: Populate the HumanResources. double-click SelectCandidates. . 7. Examine the XML record to confirm that it is complete and accurate. ensure that SQL Server files is selected. in the second row. The Add Existing Item . click Connect. On the File menu.sql. click the <Resume> field. Type the following Transact-SQL code: USE AdventureWorks2008 GO SELECT * FROM HumanResources. In the Solution Explorer. right-click Job Candidate History. On the toolbar. Click AddCandidate. point to Add. 3. 6. 10. click Execute. in the first row. click Execute. Navigate to the E:\Mod05\Labfiles\Starter folder. and then click Existing item.sql. 13.16 Lab Answer Key: Using XML 16. 20. Examine the Message box and verify that the script completed without any errors. 11.

3. the student has created and applied an XML schema and stored XML natively in the database. On the File menu. On the File menu.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT NationalIDNumber. In the Solution Explorer pane. You will use it in the next exercise. Exercise 3: Using XQuery with XML Methods Task 1: Retrieve the resume elements 1. Results: After this exercise. click Execute.microsoft. 4. click Save SQLQuery5. The Save File As dialog box appears. If the Connect to Server dialog box appears. right-click Queries. Resume. Examine the Results and Messages boxes and verify that the script completed without any errors. enter the following code to retrieve the resume elements: USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas. Keep the SQL Server Management Studio solution open. 7. On the toolbar. click Connect. and then click Save. Verify that the desired results are returned. click Save All. Note: This is the end of the first part of the module and the remaining exercises will come after the rest of the presentation. . type xmlMethods. 15. In the query window. 8. and then click New Query.JobCandidateHistory GO 6.Lab Answer Key: Using XML 17 14.query(' /RES:Resume/RES:Name ') as Result FROM HumanResources. In the File name field. 2.sql.sql As. 5.

Task 3: Update a candidate's address 1.JobCandidateHistory table.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") UPDATE HumanResources. type the following Transact-SQL code: USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT Resume. click Execute. Verify that the desired results are returned. .JobCandidateHistory WHERE JobCandidateID = 2 GO This retrieves a single resume address with a JobCandidateID of 2.18 Lab Answer Key: Using XML Task 2: Retrieve the address for a specified candidate 1.Street)[1] with "7194 Fourth St. Rockhampton"') WHERE JobCandidateID = 2 GO 2.JobCandidateHistory SET Resume. Below the previous SELECT statement. setting the Address element value in the document for the record with a JobCandidateID of 2 to 7194 Fourth St. Select the statements you just added. Rockhampton.microsoft.modify('replace value of (/RES:Resume/RES:Address/RES:Addr. and then on the toolbar.value( '(/RES:Resume/RES:Address/RES:Addr. 'nvarchar(100)') As ResumeAddress FROM HumanResources. This updates the HumanResources. 3. 2.Street)[1]'.microsoft. Below the SELECT statement. type the following Transact-SQL code: USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.

The Save File As dialog box appears. click Execute. click Save SQLQuery6. click Connect. If the Connect to Server dialog box appears. In the File name field. On the File menu. 2. On the File menu. Keep the SQL Server Management Studio solution open. Select the statements from Task 2. right-click Queries. 4. and then on the toolbar. type CreateXMLIndexes. You will use it in the next exercise. 5.Lab Answer Key: Using XML 19 3. Task 4: Verify the updated candidate's address 1. click Save All. 4. Exercise 4: Create XML Indexes Task 1: Create a new query file 1. you have used XQuery with XML methods to view the selected contents of an XML schema and modified an XML object. 4. 2. Results: After this exercise. On the toolbar. 3. Rockhampton. Examine the Messages box and verify that the script completed without any errors.sql As. 3. Verify that the desired results are returned as 7194 Fourth St. click the Execute button. In the Solution Explorer pane.sql. and then click New Query. Select the statements you just added. and then click Save. .

click Save All. Close SQL Server Management Studio. Turn off 6232A-NY-SQL-01 and delete changes. 5. type the following code to create the secondary path XML index on the Diagram column of the Production. click Execute to execute the query. below the existing code. In the query window.Illustration | Indexes.Illustration table: USE AdventureWorks2008 GO SET ARITHABORT ON CREATE PRIMARY XML INDEX PXML_Illustration_Diagram ON Production.Illustration table: CREATE XML INDEX XMLPATH_Illustration_Diagram ON Production.Illustration (Diagram) USING XML INDEX PXML_Illustration_Diagram FOR PATH WITH (FILLFACTOR = 70. 7. type the following code to create the primary XML index on the Diagram column of the Production. In the navigation pane. 4. expand Databases | AdventureWorks2008 | Tables | Production. 9. 8. Examine the Messages box and verify that the script completed without any errors. In the query window. Results: After this exercise. PAD_INDEX = ON) 2. PAD_INDEX = OFF) GO 3. . Verify that the new XML indexes are listed and are correct.Illustration (Diagram) WITH (FILLFACTOR = 60. On the File menu.20 Lab Answer Key: Using XML Task 2: Create XML indexes 1. On the toolbar. 6. you have created XML indexes.

Lab Answer Key: Implementing Views 1 Module 6 Lab Answer Key: Implementing Views Contents: Exercise 1: Creating Views Exercise 2: Creating Indexed Views Exercise 3: Creating Partitioned Views 2 5 6 .

type CreateEmployeeView. 14. . point to New. right-click Queries. 10. In the Templates box. type E:\Mod06\Labfiles\Starter. The Connect to Server dialog box appears. 8.sql. In the Location field. 6. The New Project dialog box appears. 9. 3. If the Connect to Server dialog box appears. In the Lab Launcher. Click Connect. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio. 7. click Connect. click Launch.2 Lab Answer Key: Implementing Views Lab: Implementing Views Exercise 1: Creating Views Task 1: Create a SQL Server Scripts project 1. Click OK. type AW_Views. Log on to NY-SQL-01 as Administrator using the password Pa$$w0rd. 11. In the Name field. 12. In the Solution Explorer pane. click Save SQLQuery1. On the File menu. make sure SQL Server Scripts is highlighted. and then click New Query.sql As. 4. 2. 5. In the File name field. Clear the Create directory for solution check box. next to 6232A-NY-SQL-01. 13. and then click Project. On the File menu. and then click Save. The Save File As dialog box appears.

c.Person c ON c.CountryRegionCode = sp.Name AS CountryRegionName .c.e.cr.FirstName .Title .JobTitle . On the File menu.Suffix .MiddleName .Name AS StateProvinceName .vEmployeeDetails WITH SCHEMABINDING AS SELECT e.BusinessEntityID = e.BusinessEntityID INNER JOIN Person.AddressID INNER JOIN Person.a.vEmployeeDetails view is listed.sp.a. Verify that the HumanResources.BusinessEntityAddress ea ON e.c. 6.EmailPromotion .AdditionalContactInfo FROM HumanResources.StateProvinceID INNER JOIN Person.c. click Execute.AddressID = a.Lab Answer Key: Implementing Views 3 Task 2: Create the HumanResources.StateProvinceID = a.c.vEmployeeDetails view: USE AdventureWorks2008 GO CREATE VIEW HumanResources. type the following Transact-SQL code to create the HumanResources. On the toolbar.CountryRegion cr ON cr. 3.a.AddressLine1 . 5.AddressLine2 .City .Employee e INNER JOIN Person.a. Examine Messages box and verify that the script completed without any errors.CountryRegionCode 2. . In Object Explorer.PostalCode . click Save All. BusinessEntityID INNER JOIN Person. 4.vEmployeeDetails view 1. In the query window.LastName . expand Databases | AdventureWorks2008 | Views. BusinessEntityID = ea.BusinessEntityID .c.Address a ON ea.c.StateProvince sp ON sp.

If the Connect to Server dialog box appears. In the Solution Explorer. click Connect. 2. Examine the Results and Messages boxes and verify that the script completed without any errors. right-click Queries.vEmployeeDetails 6. Results: After this exercise. 8. Task 3: Test the HumanResources.vEmployeeDetails view 1. You will use it in the next exercise. In the File name field. click Execute. 3. click Save SQLQuery2. type the following code: Use AdventureWorks2008 SELECT * FROM HumanResources.vEmployeeDetails | Columns. Verify that correct data is returned from the view. On the toolbar. 4. Verify that the correct columns are listed in the view. 10.sql. 5. The Save File As dialog box appears. . type TestEmployeeView. and then click Save. 8. you should have created and tested of a new view for the database. Keep the SQL Server Management Studio solution open. On the File menu. In the query window. click Save All. 9.4 Lab Answer Key: Implementing Views 7.sql As. In Object Explorer. 7. and then click New Query. expand Databases | AdventureWorks2008 | Views | HumanResources. On the File menu.

and then expand Indexes. USE AdventureWorks2008 GO CREATE UNIQUE CLUSTERED INDEX IX_vEmployeeDetails ON HumanResources. On the File menu.vEmployeeDetails view. click Connect. You will use it in the next exercise. On the File menu.sql. In the File name field. under Databases. Verify that the IX_vEmployeeDetails index is listed. If the Connect to Server dialog box appears. and then click Save. type the following Transact-SQL code to create the IX_vEmployeeDetails index on the HumanResources. click Execute. click Save All. 3. Results: After this exercise. .sql As. 4. 2. 4. Examine Messages box and verify that the script completed without any errors. Task 2: Create the IX_vEmployeeDetails index 1. In Object Explorer. 7. Keep SQL Server Management Studio open. In the Solution Explorer pane.Lab Answer Key: Implementing Views 5 Exercise 2: Creating Indexed Views Task 1: Create a new query file 1.vEmployeeDetails (BusinessEntityID) 2. right-click Queries.vEmployeeDetails are expanded. The Save File As dialog box appears. ensure that AdventureWorks2008 | Views | HumanResources. click Save SQLQuery3. you should have created a new view index. 5. 3. On the toolbar. In the query window. 6. and then click New Query. type CreateViewIndex.

Contact 2. Task 3: Create the Person. Task 2: Create a new query file 1. click Save All. navigate to the E:\Mod06\Labfiles\Starter folder.vContact distributed partitioned view 1. In the Solution Explorer pane. In Object Explorer. On the File menu. 4. Click Start.cmd to run the script that configures the servers for the partitioned view. type CreatePartitionedView. click Connect. right-click Databases.AW_Contacts. The Save File As dialog box appears. On the File menu. When the script completes. close Windows Explorer. 2. 2. In the query window. and then click Save.Person. On the toolbar. Double-click LabSetup.6 Lab Answer Key: Implementing Views Exercise 3: Creating Partitioned Views Task 1: Prepare the SQL Server instances 1. 4. 3. In the File name field. and then click Computer. click Execute.AW_Contacts.AW_Contacts.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE3]. type the following code to create the distributed partitioned view named Person. and then click New Query. click Save SQLQuery4.vContact AS SELECT * FROM [NY-SQL-01].vContact on the AW_Contacts database: USE AW_Contacts GO CREATE VIEW Person. 3.sql As.Person. and then click Refresh.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE2]. If the Connect to Server dialog box appears. right-click Queries. 3. 4. In Microsoft® Windows® Explorer. .sql.

you should have configured and tested a new partitioned view for the SQL Server. In Object Explorer. click Connect.Contact tables on all three SQL Server instances. 11. and then expand Views.vContact 14. Turn off 6232A-NY-SQL-01 and delete changes. . under Databases.vContact view: USE AW_Contacts GO SELECT * FROM Person. 7. 8. Under Databases. In the query window. The Save File As dialog box appears.sql. 6. Examine the Results and Messages boxes and verify that the script completed without any errors. In the Solution Explorer pane. expand Person. and then click Save. On the toolbar. click Execute. Close SQL Server Management Studio. and then expand Columns. In the File name field. click Save All. On the File menu. right-click Queries. click Save SQLQuery5. 10.sql As. Results: After this exercise. 16. expand AW_Contacts. ensure that AW_Contacts | Views are expanded. 19.Lab Answer Key: Implementing Views 7 5. 9.vContact. If the Connect to Server dialog box appears. 12. 13. type the following code to select the contents of the Person.vContact view contains the data from the Person. and then click New Query.vContact view is listed. On the File menu. 15. Verify that the result set of the Person. type ViewPersonContact. Verify that the Person. 17. Verify that the correct columns are listed. 18.

Lab Answer Key: Implementing Stored Procedures 1 Module 7 Lab Answer Key: Implementing Stored Procedures Contents: Exercise 1: Creating Stored Procedures Exercise 2: Working with Execution Plans 2 4 .

click Execute.ssmssqlproj project file. If the Connect to Sever dialog box appears. In the Solution Explorer. If the Solution Explorer is not visible in the right pane. right-click Computer and then click Explore. double-click the StoredProcedures. 5. 10. On the toolbar. Select the Use AdventureWorks2008 statement. next to 6232A-NY-SQL-01. 13. If the Connect to Sever dialog box appears. 9.2 Lab Answer Key: Implementing Stored Procedures Lab: Implementing Stored Procedures Exercise 1: Creating Stored Procedures Task 1: Create and test the GetDiscounts stored procedure 1. click View | Solution Explorer. 7. and then on the toolbar. 3. . Click Start. Double-click the AWProgrammability. connect to server NY-SQL-01 using Windows Authentication. On the toolbar. 8. 14. The Microsoft SQL Server Management Studio window opens. 4. In Windows Explorer browse to E:\MOD07\Labfiles\Starter. double-click InitilizeData. Select the text between the --Create GetDiscount comment and the following comment. connect to server NY-SQL-01 using Windows Authentication. 12. 2. Click Connect. 11. In the Lab Launcher. 6. Click Connect. click Execute. In Solution Explorer. and then confirm that no errors occur. click Launch. click the Execute button to execute the selected text. Log on as Student with the password of Pa$$w0rd.sql query file.sql.

Select the text between the --Create GetDiscountsForCategory comment and the following comment. click the Execute button. Verify the query runs with no errors. 17. 8. click the Execute button. 2. click the Execute button to execute the selected text. On the toolbar.Test GetDiscountsForCategory comment and the following comment. Task 3: Create and test the GetDiscountsForCategoryAndDate stored procedure 1. On the toolbar. Select the text between the --Create GetDiscountsForCategoryAndDate comment and the following comment. 4. 16. 4. On the toolbar. .Test GetDiscountsForCategoryAndDate with both parameters and the following comment. 7. 3. Verify the query runs with no errors. click the Execute button. click the Execute button to execute the selected text To test the GetDiscountsForCategoryAndDate stored procedure: select the text between the -. On the toolbar. On the toolbar. To test the GetDiscount stored procedure: select the text between the – Test GetDiscounts comment and the following comment. Verify the query runs with no errors.Test GetDiscountsForCategoryAndDate comment and the following comment.Lab Answer Key: Implementing Stored Procedures 3 15. Select the text between the comment -. To test the GetDiscountsForCategory stored procedure: select the text between the -. On the toolbar. Task 2: Create and test the GetDiscountsForCategory stored procedure 1. click the Execute button. 5. 6. 3. 5. Verify the query runs with no errors. 2.

click Execute. click Execute. 5. On the toolbar. 6. In the Query window. Observe in the results pane both the query and the text based execution plan are displayed instead of query results. 2. Results: After this exercise. Select the text between the – Create AddDiscount comment and the following comment. select the code between the comment –Test the textbased execution plan and the following comment. 2. In the Query window. select the code between the comment –Test the graphical execution plan and the following comment. . 3. and then click Execute. On the toolbar. On the toolbar. select all code between the comments -.4 Lab Answer Key: Implementing Stored Procedures Task 4: Create and test the AddDiscount stored procedure 1.Test AddDiscount comment and the following comment.Test AddDiscount with errors and the following comment. 4. 3. On the toolbar. 4. click the Execute button. 3. you should have created and tested 4 stored procedures. click the Execute button to execute the selected text. Task 2: View the graphical execution plan 1. Right-click the selection and then click Include Actual Execution Plan. Exercise 2: Working with Execution Plans Task 1: View the text-based execution plan 1. Observe that the execution plan displays query parts in hierarchical order from most to least expensive operation. 7. To test executing the query with variables that generate an error. 2. To test the AddDiscount stored procedure: select the text between the -. Verify the query runs with no errors. Verify that an error log record is returned in the results pane.

. you should have created and viewed both text-based and graphical execution. In the Results pane observe that query results are returned. Create an index on Name and the following comment. Task 4: View the revised execution plan 1. that 68% of the work was involved in the sort and 32% was involved in the clustered index scan. 3. Results: After this exercise. On the toolbar. 6. 6. 2. In the toolbar. observe that query results are returned.Lab Answer Key: Implementing Stored Procedures 5 4. Observe the Execution Plan tab above the returned results. that 68% of the work was involved in the sort and 32% was involved in the clustered index scan. Task 3: Tune the database to improve performance 1. In the Results pane. click Execute. 5. Click the Execution Plan tab. click Execute. In the Query window select the code below the comment –Retest the graphical execution plan. Observe that the execution plan shows that 0% of the execution’s work was involved in the SELECT statement. 2. 4. Click the Execution Plan tab. Observe that the execution plan shows that 0% of the execution’s work was involved in the SELECT statement. 5. Observe the Execution Plan tab above the returned results. In the Query window select the code between the comment --Tune the database. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab.

Lab Answer Key: Implementing Functions 1 Module 8 Lab Answer Key: Implementing Functions Contents: Exercise 1: Creating Functions Exercise 2: Controlling Execution Context 2 7 .

12. 2. next to 6232A-NY-SQL-01. Browse to E:\MOD08\Labfiles\Starter. and then click Explore.vbs. 8. In the Lab Launcher. 4. right-click Computer. If the Solution Explorer is not visible in the right pane. 11. Click OK. Type sqlcmd -E -i changeAW2008dbowner. browse to E:\MOD08\Labfiles\Starter. Double-click createnewuser. Double-click InitilizeData. If the Connect to Sever box appears. From the Start Menu. The SQL Server Management Studio window opens. 17. and then confirm that no errors occur. click Launch. 10. In Windows Explorer. 16. 6. 3.sql and then press ENTER. Double-click the AWProgrammability solution file. Open Command Prompt. From the Start Menu. Log off Administrator and then log on as Student with the password of Pa$$w0rd. The query appears. In Windows Explorer. On the toolbar.2 Lab Answer Key: Implementing Functions Lab: Implementing Functions Exercise 1: Creating Functions Task 1: Create and test the GetMaximumDiscountForCategory Userdefined function 1. connect to server NY-SQL-01 using Windows Authentication.sql. In the Solution Explorer. browse to E:\MOD08\Labfiles\Starter. 14. In Solution Explorer. click View | Solution Explorer in the File menu. 7. expand AWProgramability | Queries. right-click Computer. and then click Explore. . 5. double-click the UserDefinedFunctions. 9.sql query file. Log on as Administrator with the password of Pa$$w0rd. 13. 15. click Execute.

verifying that the statement executed successfully. 19. On the toolbar. review the query results. On the Toolbar.GetMaximumDiscountForCategory comment. 25. Select the CREATE FUNCTION code shown in the following Transact-SQL example: CREATE FUNCTION Sales. and then test the function. click Save UserDefinedFunctions. In the Results pane. Select the Use AdventureWorks2008 statement. click Execute. . Locate the Test Sales. and then on the toolbar. verify that a discount value is returned.Lab Answer Key: Implementing Functions 3 18.GetMaximumDiscountForCategory comment. 20. Select the query. click Execute. as shown in the following Transact-SQL example: SELECT Sales. If the Connect to Sever box appears.sql.GetMaximumDiscountForCategory('Reseller') 24. 23. connect to server NY-SQL-01 using Windows Authentication. In the Query results.SpecialOffer WHERE Category = @Category AND GetDate() BETWEEN StartDate AND EndDate GROUP BY Category IF (@Max IS NULL) SET @Max = 0 RETURN @Max END 21. Locate the Create Sales. 22. click Execute. On the File menu.GetMaximumDiscountForCategory (@Category nvarchar(50)) RETURNS smallmoney AS BEGIN DECLARE @Max smallmoney SELECT @Max = MAX(DiscountPct) FROM Sales.

Locate the Test Sales.4 Lab Answer Key: Implementing Functions Task 2: Create and test the GetDiscountsForDate User-defined function 1. verifying that the statement executed successfully. On the File menu.GetDiscountsForDate comment. click Execute. select the TransactSQL statement shown below in the following Transact-SQL example: SELECT * FROM Sales. MinQty.GetDiscountsForDate (@DateToCheck datetime) RETURNS TABLE AS RETURN ( SELECT Description. and then create the user-defined function. StartDate. click Save UserDefinedFunctions. verify that some rows are displayed.GetDiscountsForDate comment. DiscountPct. Category.SpecialOffer WHERE @DateToCheck BETWEEN StartDate AND EndDate ) 2. In the query results. .sql. On the toolbar. Type. EndDate. Locate the Create Sales. 4. review the query results. Select the CREATE FUNCTION statement. as shown in the following Transact-SQL example: CREATE FUNCTION Sales. 3. MaxQty FROM Sales.GetDiscountsForDate(GetDate()) ORDER BY DiscountPct DESC 5. click Execute. In the Results pane. 6. On the toolbar.

SpecialOfferID INNER JOIN Production. SO. SO.ListPrice * SO.Product P ON SOP.Description.SpecialOfferID = SO.GetDiscountedProducts (@IncludeHistory bit) RETURNS @tbl_products TABLE (ProductID int.ProductID.DiscountPct FROM Sales. P.DiscountPct.ListPrice * . SO. P.DiscountPct.ProductID.ProductID WHERE (SO. P.ListPrice * SO.Name.ListPrice . ListPrice money.Name.DiscountPct.SpecialOffer SO ON SOP. Name nvarchar(50).DiscountPct > 0) ORDER BY ProductID ELSE INSERT @tbl_products SELECT P.ListPrice . DiscountPercentage smallmoney. DiscountedPrice money) AS BEGIN IF (@IncludeHistory = 1) INSERT @tbl_products SELECT P.ListPrice. P.P. DiscountAmount money.SpecialOfferProduct SOP INNER JOIN Sales.Lab Answer Key: Implementing Functions 5 Task 3: Create and test the GetDiscountedProducts User-defined function 1. SO. P. P.ProductID = P. P.GetDiscountedProducts comment.Description.ListPrice * SO.DiscountPct.ListPrice. DiscountDescription nvarchar(255). Locate the Create Sales.P. Select the code to create the user-defined function as shown in the following Transact-SQL example: CREATE FUNCTION Sales. P.

GetDiscountedProducts(0) SELECT * FROM Sales.DiscountPct FROM Sales. On the toolbar. .SpecialOfferProduct SOP INNER JOIN Sales.SpecialOffer SO ON SOP.ProductID WHERE (SO.SpecialOfferID INNER JOIN Production. In the Results pane. click Save UserDefinedFunctions.sql. 4.GetDiscountedProducts comment. On the toolbar. view the number of rows returned by each query. Locate the Test Sales. you should have created and tested 3 user-defined functions. review the query results. click Execute.ProductID = P. 6. Verify that the statement executed successfully. 3.DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END 2. Results: After this exercise. In the query results.Product P ON SOP.GetDiscountedProducts(1) 5.SpecialOfferID = SO.6 Lab Answer Key: Implementing Functions (continued) SO. select the code as shown in the following Transact-SQL example: SELECT * FROM Sales. On the File menu. click Execute.

CurrencyAlternateKey = @CurrencyCode ORDER BY CR.sql query file. double-click the ExecutionContext. 2. On the toolbar. as shown in the following Transact-SQL example: SELECT Sales.GetCurrencyRate (@CurrencyCode nchar(3)) RETURNS float WITH EXECUTE AS 'Adam' AS BEGIN DECLARE @CurrencyRate float SELECT @CurrencyRate = (SELECT TOP (1) EndOfDayRate FROM AdventureWorksDW2008. 4. review the query results.GetCurrencyRate comment. In the Results pane.GetCurrencyRate comment. and then create the userdefined function.dbo.DimCurrency C INNER JOIN AdventureWorksDW2008. click Execute. Verify that the statement executed successfully. click Execute.CurrencyKey WHERE C. 6. as shown in the following Transact-SQL example: CREATE FUNCTION Sales.dbo.0 RETURN @CurrencyRate END GO 5. 7. In Solution Explorer.CurrencyKey = CR.GetCurrencyRate('GBP') .Lab Answer Key: Implementing Functions 7 Exercise 2: Controlling Execution Context Task 1: Create the GetCurrencyRate User-defined function 1.DateKey DESC) IF (@CurrencyRate IS NULL) SET @CurrencyRate = 1. and then test the function. If the Connect to Sever box appears. Locate the Create Sales. connect to server NY-SQL-01 using Windows Authentication. Locate the Test Sales. 3. Select the USE AdventureWorks2008 statement. Select the CREATE FUNCTION statement.FactCurrencyRate CR ON C. On the toolbar.

database_principals WHERE name = 'Adam' AND type = 'U') CREATE USER Adam FOR LOGIN [NY-SQL-01\Adam] GO 5. 7.sql query file. Select the IF and CREATE statements. Note: At this stage you have not established a trust relationship between the databases. 9. Implement the Transact-SQL code required to grant the mapped user AUTHENTICATE permission in the AdventureWorksDW2008 database. Locate the Create the user for the NY-SQL-01\Adam login comment. click Save ExecutionContext. click Execute. as shown in the following Transact-SQL example: GRANT AUTHENTICATE TO Adam GO .sql. Select the USE AdventureWorksDW2008 statement. 4. On the toolbar.8 Lab Answer Key: Implementing Functions 8. 3. and then create a user called Adam in the AdventureWorksDW2008 database for the NY-SQL-01\Adam login. 6. so you should expect to receive the following error message: The server principal "NY-SQL-01\Adam" is not able to access the database "AdventureWorksDW" under the current security context. 2. connect to server NY-SQL-01 using Windows Authentication. Click Execute. On the toolbar. as shown in the following Transact-SQL example: IF NOT EXISTS (SELECT * FROM sys. Verify that the statements executed successfully. 8. Task 2: Establish a database trust relationship 1. Select the SELECT statement. double-click the TrustRelationship. On the File menu. Locate the Grant AUTHENTICATE permission on the database comment. click Execute. In Solution Explorer. If the Connect to Sever box appears.

Locate the Grant SELECT permissions to Adam comment. Verify that the statement executed successfully. On the toolbar. On the toolbar. Locate the Set the TRUSTWORTHY database option on the AdventureWorks2008 database comment. On the toolbar. as shown in the following Transact-SQL example: ALTER DATABASE AdventureWorks2008 SET TRUSTWORTHY ON GO 15. 17. Select the GRANT statement. 13. 16. click Execute. . click Execute. click Execute. Select the GRANT statement. GRANT SELECT TO Adam GO 12.sql. Verify that the statement executed successfully.Lab Answer Key: Implementing Functions 9 9. and then implement the Transact-SQL code required to grant the authenticator the permissions required by the user-defined function in the calling database. 11. Select the ALTER statement. 14. 10. as shown in the following Transact-SQL example. and then implement the TransactSQL code required to alter the calling database and set the TRUSTWORTHY option to ON. On the File menu. click Save TrustRelationship. Verify that the statement executed successfully.

2. Locate the Sales.ProductID WHERE (SO.DiscountPct. P.ListPrice * @CurrencyRate.DiscountPct.ListPrice * SO. DiscountAmount money. CurrencyPrice money.Sales. DiscountedCurrencyPrice money) AS BEGIN DECLARE @CurrencyRate float SET @CurrencyRate = Sales. In Solution Explorer.Description.ListPrice * SO.ProductID = P. Select the USE AdventureWorks2008 statement. P.sql query file.P. click Execute. Name nvarchar(50). double-click the ExecutionContext.10 Lab Answer Key: Implementing Functions Task 3: Create and test the GetCurrencyDiscountedProducts Userdefined Function 1.GetCurrencyDiscountedProducts comment. ListPrice money. (P. DiscountPercentage smallmoney. 3.GetCurrencyDiscountedProducts (@CurrencyCode nchar(3)) RETURNS @tbl_products TABLE (ProductID int.DiscountPct) * @CurrencyRate FROM Sales.DiscountPct. On the toolbar.Name. DiscountDescription nvarchar(255). as shown in the following example: -.ListPrice * SO.GetCurrencyRate(@CurrencyCode) INSERT @tbl_products SELECT P.ListPrice .SpecialOfferProduct SOP INNER JOIN Sales. P.ListPrice . DiscountedPrice money.GetCurrencyDiscountedProducts CREATE FUNCTION Sales. SO. P.ListPrice.Product P ON SOP.SpecialOffer SO ON SOP.DiscountPct > 0) AND GetDate() BETWEEN StartDate AND EndDate ORDER BY ProductID RETURN END GO .P. SO.SpecialOfferID = SO.ProductID. P.SpecialOfferID INNER JOIN Production.

On the toolbar. 10.Lab Answer Key: Implementing Functions 11 4. Review the query results and verify that the statement executed successfully. and then test the function. On the File menu. Select the CREATE FUNCTION statement. 5. . click Save All. Locate the Test Sales. click Execute. and then close SQL Server Management Studio.GetCurrencyDiscountedProducts comment. Results: After this exercise. Turn off 6232A-NY-SQL-01 virtual machine and discard any changes.GetCurrencyDiscountedProducts('GBP') 7. On the toolbar. click Execute. Select the SELECT statement. 9. 6. 8. you should have created two user-defined functions and created a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008. Verify that the statement executed successfully. as shown in the following Transact-SQL example: SELECT * FROM Sales.

Lab Answer Key: Implementing Managed Code in a Database 1 Module 9 Lab Answer Key: Implementing Managed Code in a Database Contents: Exercise 1: Importing an Assembly Exercise 2: Creating Managed Database Objects 2 4 .

next to 6232A-NY-SQL-01. click Launch. and then click Connect. point to All Programs. specify the values in the following table. and then click SQL Server Management Studio™.2 Lab Answer Key: Implementing Managed Code in a Database Lab: Implementing Managed Code in a Database Exercise 1: Importing an Assembly Task 1: Start the NY-SQL-01 virtual machine and log on as Administrator 1. 2. Click Start. point to Microsoft® SQL Server® 2008. 3. Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication . Log on to NY-SQL-01 as Administrator using the password of Pa$$w0rd. In the Connect to Server dialog box. 4. In the Lab Launcher.

click Solution Explorer. click Save ImportAssembly. you should have the managed database objects in the AWorksUtilities assembly available for use within the AdventureWorks2008 database. browse to the E:\MOD09\Labfiles\Starter folder click the AWorks_CLR. 4. 11. verify that the statements executed successfully. Below the Create assembly comment. add the following code: sp_configure 'clr enabled'. If Solution Explorer is not visible.sql. On the File menu. 1 GO RECONFIGURE GO 8. 6. double-click the ImportAssembly. and then verify that the statements executed successfully. 5. and then on the toolbar. and then click Project/Solution.sql query file. click Execute.sql query file. 9. 3.dll' 10. In the Open Project dialog box. On the toolbar. and then confirm that no errors occur. Results: After this exercise. You will use it in the next exercise. On the File menu. 2. Below the Create assembly comment. on the View menu. click Execute. click Execute. . Below the Enable CLR integration comment. expand the Queries node. select all the code. 7.ssmssln file. and then click Open. On the toolbar. Keep the SQL Server Management Studio solution open. In the query results. In Solution Explorer. add the following code: USE AdventureWorks2008 CREATE ASSEMBLY AWorksUtilities FROM 'E:\MOD09\Labfiles\Starter\AWorksUtilities. and then double-click the Initialize. In Solution Explorer. 13. point to Open. 12.Lab Answer Key: Implementing Managed Code in a Database 3 Task 2: Import the AWorksUtilities assembly 1.

click Execute.SaveXML GO 3. Below the Retest managed stored procedure comment.sql query file. .SaveXML ( @XmlData xml. and then on the toolbar. Locate the Create managed stored procedure comment. select the DECLARE. double-click the SaveXML. 9. In the query results. Below the Change security permissions to allow file access comment. SET. Confirm that an error message is displayed. 4. click Execute. verify that the statements executed successfully. 7. Below the Test managed stored procedure comment. 11. click Execute. and then on the toolbar. 10. Below the Create managed stored procedure comment. add the following code: ALTER ASSEMBLY AWorksUtilities WITH PERMISSION_SET = EXTERNAL_ACCESS GO 8. and then on the toolbar. and then add the following code: USE AdventureWorks2008 GO CREATE PROCEDURE dbo. 6. 5. and EXEC statements. select the code. In Solution Explorer. and then on the toolbar. The assembly does not have the required permissions to write to the file system. select the DECLARE. 2.4 Lab Answer Key: Implementing Managed Code in a Database Exercise 2: Creating Managed Database Objects Task 1: Create the SaveXML managed stored procedure referencing the external assembly 1. Verify that the statements executed successfully. and EXEC statements. SET. @FileName nvarchar(100) ) AS EXTERNAL NAME AWorksUtilities. Select the ALTER ASSEMBLY statement.StoredProcedures. Confirm that no errors occur this time. click Execute.

and then verify the existence of the Output. In Microsoft Windows Explorer. 13. browse to the E:\MOD09\Labfiles\Starter folder. 17.Lab Answer Key: Implementing Managed Code in a Database 5 12. . click Save SaveXML.sql. On the File menu. Keep the SQL Server Management Studio solution open. Double-click the Output. 14. You will use it in the next procedure. and then click Computer. Click Start.xml file to display the XML in Microsoft Internet Explorer®. 16. 15. Close Internet Explorer and Windows Explorer when you have confirmed that the file contains XML.xml file.

GetLongDate ( @DateVal datetime ) RETURNS nvarchar(50) AS EXTERNAL NAME AWorksUtilities.sql. 8. click Execute.sql query file. Below the Test managed user-defined function comment. select the code. and then on the toolbar.GetLongDate GO 3.6 Lab Answer Key: Implementing Managed Code in a Database Task 2: Create the GetLongDate managed user-defined function referencing the external assembly 1. 2. 5. Below the Create managed user-defined function comment. and then on the toolbar. Confirm that the records are displayed with a long OrderDate value. Verify that the statements executed successfully. select the SELECT statement.UserDefinedFunctions. . 6. add the following code: USE AdventureWorks2008 GO CREATE FUNCTION dbo. In Solution Explorer. double-click the GetLongDate. click Execute. 4. Below the Create managed user-defined function comment. click Save GetLongDate. Verify that a list of orders is displayed that includes the day of the week in the OrderDate column. On the File menu. 7.

9.sql. select the second UPDATE statement. On the File menu. click Execute. 8. This is because the managed code checks to see which columns were updated and performs the trigger logic only if the e-mail column is modified. and then on the toolbar. 5.Triggers. click Save EmailChange.Lab Answer Key: Implementing Managed Code in a Database 7 Task 3: Create the EmailChange managed trigger on the Person.EmailChange GO 3. and then on the toolbar. Verify that the statements executed successfully. 2. select the code. 4. Below the Create trigger comment.EmailAddress table referencing the external assembly 1. double-click the EmailChange. 6.EmailAddress FOR UPDATE AS EXTERNAL NAME AWorksUtilities. Below the Create trigger comment. Confirm that a message is displayed. Below the Test trigger comment. . noting the new e-mail address in the Messages pane. Confirm that there is no message because the statement did not update the email address. select the first UPDATE statement. add the following code: USE AdventureWorks2008 GO CREATE TRIGGER EmailChange ON Person. 7. Below the Test trigger comment. click Execute.sql query file. and then on the toolbar. In Solution Explorer. click Execute.

add the following code: USE AdventureWorks2008 GO CREATE AGGREGATE Concatenate(@input nvarchar(4000)) RETURNS nvarchar(4000) EXTERNAL NAME AWorksUtilities. and then on the toolbar. select the SELECT statement.sql. 2. 7. Below the Create aggregate function comment. Verify that the statements executed successfully. Below the Test aggregate function comment. 5. On the File menu. Below the Create aggregate function comment. Confirm that orders are displayed as a concatenated string for each account in the Messages pane. 6. double-click the Concatenate. select the code. click Save Concatenate. click Execute. and then on the toolbar.sql query file. In Solution Explorer. . click Execute.Concatenate GO 3. 4.8 Lab Answer Key: Implementing Managed Code in a Database Task 4: Create the Concatenate managed aggregate function referencing the external assembly 1.

7.sql query file.IPAddress GO 3. Confirm that three result sets are displayed that show the IPAddress value in various forms. you should have successfully imported assembly code and created managed database objects. Results: After this exercise. Below the Create managed user-defined type comment.Lab Answer Key: Implementing Managed Code in a Database 9 Task 5: Create the IPAddress managed user-defined type referencing the external assembly 1. Below the Create managed user-defined type comment. add the following code: USE AdventureWorks2008 GO CREATE TYPE IPAddress EXTERNAL NAME AWorksUtilities. In Solution Explorer. 6. 2. Verify that the statements executed successfully. and then on the toolbar. 4.sql. 9. double-click the IPAddress. 5. Close the SQL Server Management Studio solution. 8. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab. click Execute. select the statements. click Execute. select the code. click Save IPAddress. and then on the toolbar. Below the Test managed user-defined type comment. . On the File menu.

Lab Answer Key: Managing Transactions and Locks 1 Module 10 Lab Answer Key: Managing Transactions and Locks Contents: Exercise 1: Using Transactions Exercise 2: Managing Locks 2 5 .

4. point to Open. In the Connect to Server dialog box. and then click Connect: Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication 3. 2. . In the Open File dialog box. 2. and then click File. In the Lab Launcher. specify the values in the following table. click Launch. On the File menu. click Tran1. Task 2: Create and commit a transaction 1.2 Lab Answer Key: Managing Transactions and Locks Lab: Managing Transactions and Locks Exercise 1: Using Transactions Task 1: Start the virtual machine and log on as Administrator 1. point to All Programs. and then click Open. and then click SQL Server Management Studio. next to 6231A-NY-SQL-01. Click Start.sql. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. point to Microsoft SQL Server 2008. browse to the E:\Mod10\Labfiles\Starter folder.

10. . click Save Tran1. 11. click Close. 13. 12. Verify that the transaction count is now set to zero and the changes have been committed to the database. On the File menu. and then add a statement to start a transaction. and then click Connect: Property Server name Authentication Value NY-SQL-01 Windows Authentication 6. Click Execute to execute the script. and then add a statement to commit the changes to the database. In the Connect to Database Engine dialog box. On the File menu. Select the end transaction statement. Locate the comment START TRANSACTION HERE. specify the values in the following table. The changes made have not been committed to the database. the transaction is still active and locks are still held. Locate the comment END TRANSACTION HERE. The changes are now committed to the database.Lab Answer Key: Managing Transactions and Locks 3 5. Select the last two statements in the script. Your code should resemble the following: COMMIT TRANSACTION 8. and then click Execute.sql. 9. Your code should resemble the following: BEGIN TRANSACTION 7. and then click Execute. and then review the results. At this point.

Click Execute to execute the script. 7. Again. 6. 3. and then add a statement to roll back the changes to the database. Your code should resemble the following: ROLLBACK TRANSACTION 5. Results: After this exercise. Locate the comment END TRANSACTION HERE. specify the values in the following table. In the Open File dialog box. and then click Connect: Property Server name Authentication Value NY-SQL-01 Windows Authentication 4. browse to the E:\Mod10\Labfiles\Starter folder. 2.4 Lab Answer Key: Managing Transactions and Locks Task 3: Create and rollback a transaction 1. click Tran2. and then review the results. 8. Notice that the transaction is complete because the transaction count is zero and the changes have been cancelled. you should have committed and rolled back transactions.Person table. On the File menu. Notice that the statements update a different record in the Person. point to Open. and then click File. On the File menu.sql. In the Connect to Database Engine dialog box. Close SQL Server Management Studio. and then click Open. click Save Tran2. .sql. the SELECT statements and the @@trancount global variable show the progress of the transaction.

sql. and Recent Expensive Queries. 2. and then click Open. request_mode.Lab Answer Key: Managing Transactions and Locks 5 Exercise 2: Managing Locks Task 1: View locking information 1. and then click File. point to All Programs. browse to the E:\Mod10\Labfiles\Starter folder. On the File menu. point to Microsoft SQL Server 2008. Review the information that shows the current lock in the master database. 5. Type the following statement into the query window: SELECT resource_type. In the Open File dialog box. specify the values in the following table. and Data File I/O. Click Execute to execute the statement. click Lock1. and then click Activity Monitor.dm_tran_locks 7. and then click Connect: Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication 3. 6. Review the information that is displayed in Processes. . in the console tree. 4. and then click Query with Current Connection. and then click SQL Server Management Studio. request_status. 10. 9. ResourceWaits. point to New. On the File menu. point to Open. request_session_id FROM sys. In SQL Server Management Studio. In the Connect to Server dialog box. Click Start. 8. request_type. right-click NY-SQL-01.

20. type the following code at the end of the script. Notice that now the SPID of the second connection holds locks on various objects. Processes. Close SQL Server Management Studio without saving the changes to the files. 17.dm_tran_locks view. but there is no corresponding COMMIT TRANSACTION or ROLLBACK TRANSACTION statement to complete the transaction. 19. and then click Activity Monitor. in the console tree.sql query window. 16. Click Execute to execute the script and note the SPID of the connection. and then click Connect: Property Server name Authentication Value NY-SQL-01 Windows Authentication 12. Switch to the Lock1. and Resource Waits. right-click NY-SQL01. and then click Execute to execute the query and retrieve data from the sys. In the Connect to Database Engine dialog box. Review the information that is now displayed in Overview. .6 Lab Answer Key: Managing Transactions and Locks 11. Notice that a transaction starts with the BEGIN TRANSACTION statement. Switch back to the original query window and then click Execute to execute the query and retrieve data from the sys. 13. 14. 15. and then execute the statement: ROLLBACK TRANSACTION 18.dm_tran_locks view. Notice that the object locks acquired during the transaction have now been released. specify the values in the following table. Switch back to the original query window. In SQL Server Management Studio.

Lab Answer Key: Managing Transactions and Locks 7 Task 2: Set locking options 1. 8. and then click File. and then click Connect: Property Server name Authentication Value NY-SQL-01 Windows Authentication 6. browse to the E:\Mod10\Labfiles\Starter folder. In the Open File dialog box. specify the values in the following table.sql. 9. and then click SQL Server Management Studio. specify the values in the following table. In the Open File dialog box. click Lock2. and then click File. and then execute the query. Click Start. On the File menu. In the Connect to Database Engine dialog box. On the File menu. specify the values in the following table. In the Connect to Database Engine dialog box. point to Microsoft SQL Server 2008. and then click Open. 5. 7. 4. In the Connect to Server dialog box. browse to the E:\Mod10\Labfiles\Starter folder. Review the contents of the file. point to Open. point to Open. point to All Programs.sql. and then click Connect: Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication 3. and then click Open. click Lock1. and then click Connect: Property Server name Authentication Value NY-SQL-01 Windows Authentication . 2.

14. Switch to the LockList.8 Lab Answer Key: Managing Transactions and Locks 10. Switch to the Lock2. 13. and then click Connect: Property Server name Authentication Value NY-SQL-01 Windows Authentication 15. and then click File. In the Connect to Database Engine dialog box. which prevents other users from accessing rows that match the criteria in a WHERE clause. click LockList. Verify that the waiting transaction has been cancelled. you will execute the query. 16. Click Execute to execute the query and notice that there is an entry of WAIT in the request_status column. and then click Cancel Executing Query.sql query window. 12. which indicates that the second query is waiting for a lock to be granted before proceeding. 11. In the Open File dialog box. Continue with the exercise and do not wait for the execution to complete. On the File menu.sql. specify the values in the following table. and then click Open. . 18.sql query window. Click Execute to execute the query. 17. point to Open. Review the contents of the file and notice that the transaction isolation level is set to SERIALIZABLE. browse to the E:\Mod10\Labfiles\Starter folder. Note: In the next step. and then click Execute to execute the query.

Close SQL Server Management Studio without saving the changes to the files.sql query window. Turn off the virtual machine and delete changes. 3. Click Execute to execute the query and wait five seconds. Switch to the Lock2.Lab Answer Key: Managing Transactions and Locks 9 Task 3: Set the lock timeout 1. . Results: After this exercise. and then edit the file by adding the following statement immediately before the BEGIN TRANSACTION statement: SET lock_timeout 5000 2. Notice that the query no longer waits indefinitely for the lock to be granted. you should have set locking options and timeouts. 4.

Lab Answer Key: Using Service Broker 1 Module 11 Lab Answer Key: Using Service Broker Contents: Exercise 1: Creating Service Broker Objects Exercise 2: Implementing the Initiating Service Exercise 3: Implementing the Target Service 2 5 6 .

5. click Launch.sql. 3. If the Connect to Database Engine dialog box appears. 4. click Rename.2 Lab Answer Key: Using Service Broker Lab: Using Service Broker Exercise 1: Creating Service Broker Objects Task 1: Launch SQL Server Management Studio 1. 2. Clear Create directory for solution and then click OK. next to 6232A-NY-SQL-01. and then press ENTER. verify that Server type is set to Database Engine and Server name is set to NY-SQL-01. and then click Project. In the Location field. in the Queries folder. click Solution Explorer. click Connect. 4. In the New Project dialog box. . 2. and then click Connect. In the Connect to Server dialog box. In Solution Explorer. on the View menu. 3. 4. point to New.sql.sql. and then click SQL Server Management Studio. Click Start | All Programs | Microsoft SQL Server 2008. On the File menu. If Solution Explorer is not visible. type AW_ServiceBroker. Notice how the name of the query in the design pane has automatically changed to PrepareDatabase. in the Name field. click New Query to add a new query file to the project. 2. right-click SQLQuery1. Task 3: Configure the AdventureWorks database for Service Broker 1. Task 2: Create the AW_ServiceBroker SQL Server Scripts project 1. In the Lab Launcher. type PrepareDatabase. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. On the Project menu. 3. type E:\MOD11\Labfiles\Starter.

Enable Service Broker in the AdventureWorks2008 database ALTER DATABASE AdventureWorks2008 SET SINGLE_USER WITH ROLLBACK IMMEDIATE GO ALTER DATABASE AdventureWorks2008 SET ENABLE_BROKER GO -. click Save All. . On the toolbar.Configure the AdventureWorks2008 database USE AdventureWorks2008 GO IF NOT EXISTS (SELECT * FROM sys. [Event] nvarchar(50) NOT NULL.Create a table to log details of the customer e-mails sent CREATE TABLE EMailSvc.Lab Answer Key: Using Service Broker 3 6.symmetric_keys WHERE name = '##MS_DatabaseMasterKey##') CREATE MASTER KEY ENCRYPTION BY PASSWORD = '23987hxJ#KL95234nl0zBe' GO CREATE SCHEMA EMailSvc GO CREATE SCHEMA CustomerSvc GO -.EmailLog ( Date datetime NOT NULL. 8. click Execute to execute the query. On the File menu.sql query: USE master GO -. CustomerData xml ) GO ALTER DATABASE AdventureWorks2008 SET MULTI_USER GO 7. Add the following Transact-SQL code to the PrepareDatabase.

click Rename. click New Query. type CreateServiceBrokerObjects.NewCustomerEmailQueue WITH STATUS = OFF GO -.sql.Create contracts CREATE CONTRACT [//AW/EMail/SendCustomerDetails] ( [//AW/EMail/CustomerDetails] SENT BY INITIATOR ) GO -.NewCustomerQueue WITH STATUS = ON CREATE QUEUE EMailSvc.Create message types CREATE MESSAGE TYPE [//AW/EMail/CustomerDetails] VALIDATION = WELL_FORMED_XML GO -. contract. 2.sql query window. type the following Transact-SQL code to create the message type. and then press ENTER. In Solution Explorer. In the CreateServiceBrokerObjects.4 Lab Answer Key: Using Service Broker Task 4: Create the Service Broker objects required for the customer email solution 1.NewCustomerEmailQueue ([//AW/EMail/SendCustomerDetails]) . On the Project menu. right-click SQLQuery1. and services: USE AdventureWorks2008 GO -.NewCustomerQueue CREATE SERVICE [//AW/EMail/EmailService] ON QUEUE EMailSvc.Create services CREATE SERVICE [//AW/Sales/CustomerService] ON QUEUE CustomerSvc. queues.sql.Create queues CREATE QUEUE CustomerSvc. 3.

you should have launched SQL Server Management Studio and created the AW_ServiceBroker SQL Server Scripts project. expand Databases. on the View menu. Results: After this exercise. 8. click Execute to execute the query. click the CreateEmailNewCustomerSP. On the File menu. and then verify that the necessary Service Broker objects are listed. In Object Explorer. In the Add Existing Item – AW_ServiceBroker dialog box. and then expand Service Broker. and then click Add.sql query file to the AW_ServiceBroker project 1. 9. click Object Explorer. Exercise 2: Implementing the Initiating Service Task 1: Add the CreateEmailNewCustomerSP. 2. 5. and Services folders. Queues. you should have configured the AdventureWorks database for Service Broker and then created the Service Broker objects required for the customer e-mail solution. click Add Existing Item. Contracts. In addition. .sql query file. If Object Explorer is not visible. expand the Message Types. Keep Microsoft SQL Server Management Studio open for the next exercise. 7. On the Project menu. browse to the E:\MOD11\Labfiles\Starter folder. In the Service Broker folder. expand AdventureWorks2008. click Save All.Lab Answer Key: Using Service Broker 5 4. 6. On the toolbar.

you should have created the CustomerSvc. click Execute to execute the query. In Object Explorer. On the toolbar. On the Project menu. 2.sql query file to the AW_ServiceBroker project 1. click Save All. Exercise 3: Implementing the Target Service Task 1: Add the CreateSendEmailSP. expand Programmability. and then expand Stored Procedures. 4. under AdventureWorks2008. click Add Existing Item.uspEmailNewCustomer stored procedure used by the service. 5. Examine the Transact-SQL code in the CreateEmailNewCustomerSP. Verify that the CustomerSvc. Keep Microsoft SQL Server Management Studio open for the next exercise. Results: After this exercise.6 Lab Answer Key: Using Service Broker Task 2: Implement the CustomerService service 1.sql query file. 2.sql query file. On the File menu. Notice that it contains Transact-SQL statements to create a stored procedure that sends messages from the CustomerService service to the EmailService service in the AdventureWorks2008 database. In the Add Existing Item – AW_ServiceBroker dialog box. 6. . 3. browse to the E:\MOD11\Labfiles\Starter folder.uspEmailNewCustomer stored procedure is listed. click the CreateSendEmailSP. and then click Add.

click Save All. In Object Explorer. On the toolbar.sql query window. 5. type the following Transact-SQL statement to make the EMailSvc. click Rename.sql query file. 2. PROCEDURE_NAME = AdventureWorks2008. On the File menu.uspSendCustomerEmail.sql. 3. click Execute to execute the query. In the AlterServiceBrokerQueue. On the Project menu.NewCustomerEmailQueue queue activate the EMailSvc.EMailSvc.uspSendCustomerEmail stored procedure is listed. Verify that the EMailSvc. Examine the Transact-SQL code in the CreateSendEmailSP. MAX_QUEUE_READERS = 5. Notice that it contains Transact-SQL statements to create a stored procedure to receive and process messages in the EmailService service in the AdventureWorks2008 database. and then press ENTER. click Execute to execute the query.uspSendCustomerEmail stored procedure: USE AdventureWorks2008 GO ALTER QUEUE EMailSvc. Task 3: Configure the target service for automatic activation 1. On the File menu. and then click Refresh.Lab Answer Key: Using Service Broker 7 Task 2: Implement the EmailService service 1. In Solution Explorer.NewCustomerEmailQueue WITH STATUS = ON.sql. 5. On the toolbar. click New Query. 2. type AlterServiceBrokerQueue. right-click Stored Procedures. right-click SQLQuery1. 4. ACTIVATION ( STATUS = ON. click Save All. 3. EXECUTE AS OWNER) 4. .

Examine the TestEmailService. 7. browse to the E:\MOD11\Labfiles\Starter folder. click Execute to execute the query. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes. and notice that it contains Transact-SQL statements to execute the CustomerSvc. 4. (If the table contains no records. select the SELECT statement. and then click Add. wait a few seconds. In the Add Existing Item – AW_ServiceBroker dialog box.sql query file. 2.uspEmailNewCustomer stored procedure and then query the EMailSvc. and verify that it contains the customer data sent to the EmailService service. Results: After this exercise. 5.EmailLog table. click Add Existing Item. you should have created a stored procedure that receives and processes messages in the EmailService service. 6. On the toolbar. You should have also tested the EmailService service. click the TestEmailService.sql query file. . and then re-execute it). Review the result set returned from the EMailSvc. 3. On the File menu.8 Lab Answer Key: Using Service Broker Task 4: Test the EmailService service 1. click Save All. On the Project menu.EmailLog table.

Sign up to vote on this title
UsefulNot useful