Вы находитесь на странице: 1из 188

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

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

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. You must first use the specification to create the database with the necessary options and create the appropriate filegroups. 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, and AW_IT_Assets_log. These files should be created in the E:\MOD01\Labfiles folder. The database should use two filegroups, the primary filegroup and a filegroup named SECONDARY, which should be the default filegroup. The AW_IT_Assets_Data2 file should be placed in the SECONDARY filegroup.

Lab Instructions: Creating Databases and Database Files

Both data files should have an initial size of 20 megabytes (MB) each and should not grow automatically. The log file should have an initial size of 5 MB and should not grow automatically. The database should automatically close when no users are connected and should automatically shrink when appropriate. All scripts should be saved in a SQL Server Scripts project in the E:\MOD01\Labfiles\Scripts folder.

The main tasks for this exercise are as follows: 1. 2. Create a SQL Server Management Studio Scripts project. Create a new database by executing a SQL Server Management Studio Scripts project.

Task 1: Create a SQL Server Management Studio Scripts project


1. 2. Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd. 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. Save these scripts in a SQL Server Scripts project in the E:\MOD01\Labfiles folder.
Results: After this exercise, you should have created a new database with the appropriate options and filegroups and created a SQL Server Management Studio Scripts project.

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. In this exercise you will now create the required schemas for the new AW_IT_Assets database. The main tasks for this exercise are as follows: 1 2. 3. Create a new database user. Create a schema and assign ownership to a user. Display ownership of a schema.

Task 1: Create a new database user


Create a new database user named Katie. Do not grant Katie any permissions in the Database User window, as permissions will be added in the next task.

Task 2: Create a schema and assign ownership to a user


The database should have one user-defined schema named TechSupport. The user NY-SQL-01\Katie should use the TechSupport schema as her default schema.

Task 3: Display ownership of a schema


1. 2. 3. Create a T-SQL statement that displays ownership of the TechSupport schema. Comment the T-SQL statement to explain what it will do on execution. Execute the T-SQL statement.
Results: After this exercise, you should have created a schema and assigned ownership to a user. You should have also displayed ownership of the newly created schema.

Lab Instructions: Creating Databases and Database Files

Exercise 3: Creating a Database Snapshot


Scenario
The senior developer at Adventure Works is now requesting a database snapshot be created for reporting purposes. You will use T-SQL to write a statement that will create a database snapshot, change the current database, and then restore the database from the snapshot to undo those changes. In this exercise you will create a database snapshot, alter the database, and then revert the database to the previously created snapshot. The main tasks for this exercise are as follows: 1. 2. 3. Create a database snapshot. Alter the database. Revert the database to the previously created database snapshot.

Task 1: Create a database snapshot


A database snapshot named AW_IT_Assets_Snapshot1 must be created for reporting purposes. Using T-SQL, create a snapshot of the AW_IT_Assets database. The files for the database snapshot must be created in the E:\MOD01\Labfiles\Snapshots folder.

Task 2: Alter the database


Delete the TechSupport.Hardware table on the AW_IT_Assets database. Delete the TechSupport schema on the AW_IT_Assets database.

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. Revert the database to the AW_IT_Assets_Snapshot1 database snapshot. Notice that the TechSupport.Hardware table and TechSupport schema have both been restored.
Results: After this exercise, you should have created a database snapshot, altered the database, and then reverted the database to the database snapshot.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Creating Data Types and Tables

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

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 companys database be modified to include data about goods that have been returned and sales that have been refunded. 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. The main tasks for this exercise are as follows: 1. 2. Create a data type based on the nvarchar system-supplied data type. Create a data type based on the decimal system-supplied data type.

Lab Instructions: Creating Data Types and Tables

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. Create a new data type named ShortDescription in the dbo schema. This data type should be based on the nvarchar system-supplied data type and should have a maximum length of 100 characters.

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. 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.
Results: After this exercise, you should have successfully created a new data type based on the nvarchar system-supplied data type. 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

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. 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. The main tasks for this exercise are as follows: 1. 2. Obtain date and time formatting using T-SQL. Convert sample data into new data type formats using T-SQL.

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. Be sure to include the conversion to time, date, smalldatetime, datetime, datetime2, and datetimeoffset data types in your query.

Task 2: Convert sample data into new data type formats using T-SQL
Use '2006-04-04T15:50:59.997' as your datetime sample. Use CAST and CONVERT to convert sample data into the date format and also into the time format.
Results: After this exercise, 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.

Lab Instructions: Creating Data Types and Tables

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. The senior database developer has given you the task of creating these two tables based on the specifications provided. The main tasks for this exercise are as follows: 1. 2. Create a table named ReturnedGoods. Create a table named Refunds.

Task 1: Create a table named ReturnedGoods


The table must be created in the Sales schema. The table must contain the following columns: ReturnID. An int identity column that cannot contain NULL values. ProductID. An int column that cannot contain NULL values. CustomerID. An int column that cannot contain NULL values. ReturnDate. A datetime column that cannot contain NULL values. ReturnReason. A ShortDescription column that can 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. An int identity column that cannot contain NULL values. ReturnID. An int column that cannot contain NULL values. Amount. A CashValue column that cannot contain NULL values.

Results: After this exercise, you should have created a table named ReturnedGoods, created a table named Refunds, and followed all provided specifications.

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, specifically that the working with the Returns table is very slow. As part of the solution to this problem, 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. The main tasks for this exercise are as follows: 1. 2. 3. Prepare the database for partitioning. Create a partitioned table named ReturnsArchive. Review the partitioning implementation.

Task 1: Prepare the database for partitioning


Open the query located at E:\MOD02\Labfiles\Scripts\partition_prep.sql. Execute the query.

Task 2: Create a partitioned table named ReturnsArchive


Create a partitioned table that stores data in four partitions using the Test1FG, Test2FG, Test3FG, and Test4FG filegroups. The table must contain the following columns: ReturnID. An int identity column that cannot contain NULL values. ProductID. An int column that cannot contain NULL values. CustomerID. An int column that cannot contain NULL values. ReturnDate. A datetime column that cannot contain NULL values. ReturnReason. A ShortDescription column that can contain NULL values.

Lab Instructions: Creating Data Types and Tables

Task 3: Review the partitioning implementation


Review the Storage settings in the AdventureWorksDW2008 table properties. Note the new partitioning information under Compression, Filegroups, and Partitioning.
Results: After this exercise, you should have successfully prepared the database for partitioning, created a partitioned table named ReturnsArchive according to the specifications provided, and then reviewed the partitioning changes.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Creating and Tuning Indexes

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

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. You must implement a new unique, non-clustered index named Ix_Product_Supply_Chain on the Production.Product table to support queries that include stock-level management information. Use the following settings: Key columns: ProductNumber, Color, ReorderPoint, SafetyStockLevel Included columns: DaysToManufacture Locking: Allow row locks but not page locks. Fill factor: Set the fill factor to 90 percent on both leaf and non-leaf nodes.

Lab Instructions: Creating and Tuning Indexes

This exercises main tasks are: 1. 2. 3. Start the 6432A-NY-SQL-01 virtual machine and log on as Student. Create a SQL Server Scripts project. 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 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:/MOD03/Labfiles/Starter).

Task 3: Create the Ix_Product_Supply_Chain index


1. In the query window, enter the Transact-SQL code to create the Ix_Product_Supply_Chain index on Production.Product, columns ProductNumber, Color, ReorderPoint, and SafetyStockLevel. Include DaysToManufacture. Make sure to allow row locks, do not allow page locks, use a FILLFACTOR of 90, and pad the index. On the toolbar, click Execute.
Results: After this exercise, you should have successfully created a SQL Server Scripts project and created the Ix_Product_Supply_Chain index.

2.

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. A script has been provided to add these records. After you add the records, you need to check the indexes for fragmentation and reorganize or rebuild as needed. This exercises main tasks are: 1. 2. 3. Add the sample products to the database. Reorganize AK_Product_ProductNumber. Rebuild AK_Product_Name.

Task 1: Add the sample products to the database


In SQL Server Management Studio, open aw2008sampleproductadd.sql from the E:\Mod03\Labfiles\Starter\ folder, and then execute it. o You may ignore any errors about duplicate keys.

Task 2: Reorganize AK_Product_ProductNumber


Use SQL Server Management Studio to reorganize the AK_Product_ProductNumber index which is associated to the Production.Product table of the AdventureWorks2008 database.

Lab Instructions: Creating and Tuning Indexes

Task 3: Rebuild AK_Product_Name


Use SQL Server Management Studio to reorganize the AK_Product_Name index which is associated to the Production.Product table of the AdventureWorks2008 database.
Results: After this exercise, you should have successfully optimized the Production.Product table indexes using both reorganize and rebuild.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

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

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

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 exercises 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.

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.

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

Exercise 2: Disabling Constraints.


Scenario
Now that you have enabled constraints on your table, 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 results. This exercises main tasks are: 1. 2. 3. Insert multiple rows into the JobCandidateHistory table. Disable constraints on the JobCandidateHistory table. Enable constraints on the JobCandidateHistory table.

Task 1: Insert multiple rows into the JobCandidateHistory table


In SQL Server Management Studio, open InsertTestData.sql from the E:\Mod04\Labfiles\Starter\ folder, and then execute it with statistics enabled. Examine the performance statistics.

Task 2: Disable constraints on the JobCandidateHistory table


1. 2. 3. 4. Add a new query to the project. Change the query file name to Constraints.sql. In the query window, type the appropriate Transact-SQL to disable the constraints on the HumanResources.JobCandidateHistory table. Execute the query, and then save the query file. Open the InsertTestData.sql script, execute the query, and then compare the performance statistics for the INSERT statements before and after the constraints were disabled.

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

Task 3: Enable constraints on the JobCandidateHistory table


1. 2. In the Constraints.sql query window, type the appropriate Transact-SQL to enable the constraints on the HumanResources.JobCandidateHistory table. Execute the query, and then save the query file.
Results: After this exercise, you should have successfully compared performance results with constraints enabled and disabled.

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

Exercise 3: Creating Triggers.


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.JobCandidate table that copies the candidates information to the HumanResources.JobCandidateHistory table when somebody deletes a candidate. The JobCandidateId column must be copied directly across and the RejectedDate set to the current date by using the getdate function. Rating should be left at its default value, and ContactDetails should be set to NULL. This exercises main tasks are: 1. 2. Create the dJobCandidate trigger. Test the dJobCandidate trigger.

Task 1: Create the dJobCandidate trigger


1. 2. Add a new query to the project. Change the query file name to Trigger.sql. In the query window, type the appropriate Transact-SQL to create the dJobCandidate trigger on the HumanResources.JobCandidate table in the AdventureWorks database. Execute the query, and then save the query file. Use Object Explorer to verify that the trigger has been created.

3. 4.

Lab Instructions: Implementing Data Integrity by Using Constraints and Triggers

Task 2: Test the dJobCandidate trigger


1. 2. In SQL Server Management Studio, open the TestTrigger.sql query file from the E:\MOD04\Labfiles\Starter folder. Execute the query script, and look in the results pane to verify that the record deleted from the HumanResources.JobCandidate table has been inserted into the HumanResources.JobCandidateHistory table.
Results: After this exercise, you should have successfully created and tested the dJobCandidate trigger.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Using XML

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

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, which they will then use when picking items from the warehouse for an order delivery. The item-choosing application requires the order manifest to be downloaded as XML. You must modify the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML. Adventure Works is also creating a new ordering system for specific customers so that they can send orders as XML documents. 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. 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.

Lab Instructions: Using XML

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. The first FOR XML query should produce attribute-centric XML, 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" /> <! -- remaining items go here. --> </SalesOrder>

The second FOR XML query should produce a mixture of element-centric and attribute-centric XML, 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> <!-- more items here --> </SalesOrder>

In the FOR XML queries, the SalesOrder attributes come from the Sales.SalesOrderHeader table. The Item attributes and elements come from the Sales.SalesOrderDetail table.

Lab Instructions: Using XML

Two OPENXML queries are required to shred the XML document into the appropriate tables. The first query will insert data into the Sales.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.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, so attention needs to be placed on casing of the characters when completing these labs.

Lab Instructions: Using XML

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. Start the Server Management Studio and connect to the server. Open the project XML.ssmssln. Execute the FORXML.sql query. Modify the SELECT statement to include the FOR XML clause and return attribute-centric XML by using AUTO mode.
SELECT SalesOrder.SalesOrderID, SalesOrder.OrderDate, SalesOrder.AccountNumber, Item.ProductID, Item.OrderQty FROM Sales.SalesOrderHeader SalesOrder JOIN Sales.SalesOrderDetail Item ON SalesOrder.SalesOrderID = Item.SalesOrderID WHERE SalesOrder.SalesOrderID = 43659 FOR XML AUTO

Execute the modified code and examine the XML data. Modify the query statement.
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

Execute the modified code and examine the XML data.

Lab Instructions: Using XML

Task 2: Use the OPENXML function to insert the XML data into the tables
Open the OPENXML.sql query. Locate the comment Call stored procedure to create the memory tree, and then add a call to the sp_xml_preparedocument stored procedure.
EXEC sp_xml_preparedocument @docHandle OUTPUT, @doc

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.
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)

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.
OPENXML(@docHandle, '/SalesOrder/Item', 2) WITH ( OrderQty int, ProductID int, UnitPrice money)

Lab Instructions: Using XML

Locate the comment Call stored procedure to clean up memory tree, and then add a call to the sp_xml_removedocument stored procedure.
EXEC sp_xml_removedocument @docHandle

Execute the code and examine the results, and confirm that a new record was added to the SalesOrderHeader table and two records were added to the SalesOrderDetail table.
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.

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. 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 provided you with the Transact-SQL to create the HumanResources.JobCandidateHistory table. The senior database developer has asked you to: Create an XML schema collection named HumanResources.HistoricResumeSchemaCollection. The Human Resources department will supply the XML schema, which is a variant of the schema that the department currently uses for the resumes of active candidates. Apply the schema collection to the JobCandidateHistory.Resume column to make it typed xml data. Create a SQL Server Scripts project for the modifications by using SQL Server Management Studio, and then store the project in the E:\Mod05\Labfiles\Starter folder. A file named HistoricResumeSchema.xml containing the schema for the HistoricResumeSchemaCollection XML schema collection is provided in the E:\Mod05\Labfiles\Starter folder.

Task 1: Create a SQL Server Scripts project in SQL Server Management Studio
Create a new project. Name: Job Candidate History Location: E:\Mod05\Labfiles\Starter

Lab Instructions: Using XML

Task 2: Create the HumanResources.JobCandidateHistory table


Create a table named HumanResources.JobCandidateHistory in the AdventureWorks2008 database.
USE AdventureWorks2008 GO CREATE TABLE HumanResources.JobCandidateHistory ( JobCandidateID int IDENTITY PRIMARY KEY, BusinessEntityID int NULL, Rating int NOT NULL Default (5), RejectedDate datetime NOT NULL, NationalIDNumber nvarchar (15) NOT NULL, ModifiedDate DateTime, Resume xml ) GO

Execute the code, and then verify that the HumanResources.JobCandidateHistory table is listed. Verify that the necessary columns have been successfully created.

Task 3: Create a new query file


Create a new query file. File name: XMLSchema.sql

Task 4: Create an XML schema collection named HumanResources.HistoricResumeSchemaCollection


Add this item to the solution. File of type: XML Files Folder: E:\Mod05\Labfiles\Starter File name: HistoricResumeSchema.xml

Examine this file.

10

Lab Instructions: Using XML

Add this item to the solution. File of type: SQL Server files Folder: E:\Mod05\Labfiles\Starter File name: CreateXMLSchema.sql

Examine this file. Execute the code. Examine Messages box and verify that the script completed without any errors.

Task 5: Apply the schema collection to the JobCandidateHistory.Resume column


Create a new query. File name: AlterCandidateTable.sql

Enter the following code to alter the JobCandidateHistory table:


ALTER TABLE HumanResources.JobCandidateHistory ALTER COLUMN Resume xml (HumanResources.HistoricResumeSchemaCollection) GO

Execute the code and examine Messages box and verify that the script completed without any errors. Confirm that the HumanResources.HistoricResumeSchemaCollection is associated with the Resume column.

Task 6: Test the HistoricResumeSchema XML schema


Open the TestXMLSchema.sql file. Below the comment This should fail, select the INSERT code. Execute the code and examine the error message in the Messages pane. Below the comment This should succeed, select the code. Execute the code and verify that the script completed without any errors.

Lab Instructions: Using XML

11

Create a new query. File name: SelectCandidates.sql

Enter the following code:


USE AdventureWorks2008 GO SELECT * FROM HumanResources.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.

Task 7: Populate the HumanResources.JobCandidateHistory table with additional sample data


Open the AddCandidate.sql file. Execute the code and verify that the script completed without any errors. Open the SelectCandidates.sql file. Execute the code and verify that the script completed without any errors. Examine the xml record to confirm that it is accurate.
Results: After this exercise, the student has created and applied an XML schema and stored XML natively in the database.

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. The organization intends to deploy a new Pocket PC based application to its warehouse employees, which they will then use when picking items from the warehouse for an order delivery. The item-choosing application requires the order manifest to be downloaded as XML. You must modify the existing Transact-SQL query that generates the order manifest so that it retrieves the data as XML. Adventure Works is also creating a new ordering system for specific customers so that they can send orders as XML documents. 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.

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. You need to use XQuery expressions to retrieve and modify delivery schedule data.

Task 1: Retrieve the resume elements


Create a new query. File name: xmlMethods.sql

Enter the following code to retrieve the resume elements:


USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT NationalIDNumber, Resume.query(' /RES:Resume/RES:Name ') as Result FROM HumanResources.JobCandidateHistory GO

Execute the code and verify that the desired results are returned.

Task 2: Retrieve the address for a specified candidate


Below the SELECT statement, type the following Transact-SQL:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT Resume.value( '(/RES:Resume/RES:Address/RES:Addr.Street)[1]', 'nvarchar(100)') As ResumeAddress FROM HumanResources.JobCandidateHistory WHERE JobCandidateID = 2 GO

Execute the statements, and then verify that the desired results are returned.

14

Lab Instructions: Using XML

Task 3: Update a candidate's address


Below the previous SELECT statement, type the following Transact-SQL:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") UPDATE HumanResources.JobCandidateHistory SET Resume.modify('replace value of (/RES:Resume/RES:Address/RES:Addr.Street)[1] with "7194 Fourth St. Rockhampton"') WHERE JobCandidateID = 2 GO

Execute the statements, and then verify that the desired results are returned.

Task 4: Verify the updated candidate's address


Select the statements from Task 2. Execute the statements, and then verify that the desired results are returned as 7194 Fourth St. Rockhampton.
Results: After this exercise, you should have you have used XQuery with XML methods to view the selected contents of an XML schema and modified an XML object.

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. They want to pilot the aspect of the schema used to describe illustrations of products in XML format. 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. This will mean a dramatic increase in the use of the Production.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 the following settings: Index name: PXML_Illustration_Diagram Index type: Clustered, nonunique Fill factor: Set the fill factor to 60 percent on both leaf and non-leaf nodes

Secondary path index on the Diagram column. Use these settings: Index name: XMLPATH_Illustration_Diagram Index type: Nonclustered, nonunique Fill factor: Set the fill factor to 70 percent on leaf nodes

Task 1: Create a new query file


Create a new query. File name: CreateXMLIndexes.sql

16

Lab Instructions: Using XML

Task 2: Create XML indexes


In the query window, type the following code to create the primary XML index on the Diagram column of the Production.Illustration table:
USE AdventureWorks2008 GO SET ARITHABORT ON CREATE PRIMARY XML INDEX PXML_Illustration_Diagram ON Production.Illustration (Diagram) WITH (FILLFACTOR = 60, PAD_INDEX = ON)

In the query window, below the existing code, type the following code to create the secondary path XML index on the Diagram column of the Production.Illustration table:
CREATE XML INDEX XMLPATH_Illustration_Diagram ON Production.Illustration (Diagram) USING XML INDEX PXML_Illustration_Diagram FOR PATH WITH (FILLFACTOR = 70, PAD_INDEX = OFF) GO

Execute the code and verify that the script completed without any errors. Verify that the new XML indexes are listed and are correct.
Results: After this exercise, you have created XML indexes.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Implementing Views

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

Lab Instructions: Implementing Views

Lab: Implementing Views

Exercise 1: Creating Views


Scenario
Adventure Works finds that their database systems arent performing as well as they would like. After consultation with the Human Resources department, the senior database developer has identified a number of views that will improve database performance and simplify future development. It was also found that indexed views and partitioned views will also improve performance. 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 asked you to perform the following task: Create a new view named HumanResources.vEmployeeDetails that uses the following SELECT logic. Remember to use the SCHEMABINDING option when you create the view, because you will need to create an index on the view later.

Lab Instructions: Implementing Views

In this exercise, you must add a new view to SQL Server at the New York City location. The main tasks for this exercise are as follows: 1. 2. 3. Create a SQL Server Scripts project. Create the HumanResources.vEmployeeDetails view. Test the HumanResources.vEmployeeDetails view.

Task 1: Create a SQL Server Scripts project


1. 2. 3. Start 6232A-NY-SQL-01 and logon as Student using the password Pa$$w0rd. Start the Server Management Studio and connect to the server. Create a new project. 4. Name: AW_Views Location: E:\Mod06\Labfiles\Starter

Create a new query file. File name: CreateEmployeeView.sql

Lab Instructions: Implementing Views

Task 2: Create the HumanResources.vEmployeeDetails view


1. Type the following Transact-SQL code to create the HumanResources.vEmployeeDetails view:

USE AdventureWorks2008 GO CREATE VIEW HumanResources.vEmployeeDetails WITH SCHEMABINDING AS SELECT e.BusinessEntityID ,c.Title ,c.FirstName ,c.MiddleName ,c.LastName ,c.Suffix ,e.JobTitle ,c.EmailPromotion ,a.AddressLine1 ,a.AddressLine2 ,a.City ,sp.Name AS StateProvinceName ,a.PostalCode ,cr.Name AS CountryRegionName ,c.AdditionalContactInfo FROM HumanResources.Employee e INNER JOIN Person.Person c ON c.BusinessEntityID = e.BusinessEntityID INNER JOIN Person.BusinessEntityAddress ea ON e. BusinessEntityID = ea. BusinessEntityID INNER JOIN Person.Address a ON ea.AddressID = a.AddressID INNER JOIN Person.StateProvince sp ON sp.StateProvinceID = a.StateProvinceID INNER JOIN Person.CountryRegion cr ON cr.CountryRegionCode = sp.CountryRegionCode

2. 3. 4. 5.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that the HumanResources.vEmployeeDetails view is listed in the Object Explorer. Verify that the correct columns are listed in the view.

Lab Instructions: Implementing Views

Task 3: Test the HumanResources.vEmployeeDetails view


1. Create a new query file. 2. File name: TestEmployeeView.sql

In the blank query window, type the following code:

Use AdventureWorks2008 SELECT * FROM HumanResources.vEmployeeDetails

3. 4. 5.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that correct data is returned from the view.
Results: After this exercise, you should have created and tested of a new view for the database.

Lab Instructions: Implementing Views

Exercise 2: Creating Indexed Views


Scenario
After testing the HumanResources.vEmployeeDetails view, the senior database developer has asked you to perform the following task: Turn the HumanResources.vEmployeeDetails view into an indexed view by creating a unique clustered index named IX_vEmployeeDetails on the EmployeeID column.

In this exercise, you need to create an indexed view for the SQL Server database. The main tasks for this exercise are as follows: 1. 2. Create a new query file. Create the IX_vEmployeeDetails index.

Task 1: Create a new query file


Create a new query file. File name: CreateViewIndex.sql

Task 2: Create the IX_vEmployeeDetails index


1. In the query window, type the following Transact-SQL code to create the IX_vEmployeeDetails index on the HumanResources.vEmployeeDetails view:

USE AdventureWorks2008 GO CREATE UNIQUE CLUSTERED INDEX IX_vEmployeeDetails ON HumanResources.vEmployeeDetails (BusinessEntityID)

2. 3. 4.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that the the IX_vEmployeeDetails index is listed in Object Explorer.
Results: After this exercise, you should have created a new view index.

Lab Instructions: Implementing Views

Exercise 3: Creating Partitioned Views


Scenario
After testing the HumanResources.vEmployeeDetails view, the senior database developer has asked you to perform the following task: Create a distributed partitioned view named Person.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].AW_Contacts.Person.Contact [NY-SQL-01 \SQLINSTANCE2].AW_Contacts.Person.Contact [NY-SQL-01 \SQLINSTANCE3].AW_Contacts.Person.Contact

In this exercise, you need to configure the SQL Server databases and create a new partitioned view. The main tasks for this exercise are as follows: 1. 2. 3. Prepare the SQL Server instances. Create a new query file. Create the Person.vContact distributed partitioned view.

Task 1: Prepare the SQL Server instances


Execute the following code: E:\Mod06\Labfiles\Starter\ LabSetup.cmd

Task 2: Create a new query file


Create a new query file. File name: CreatePartitionedView.sql

Lab Instructions: Implementing Views

Task 3: Create the Person.vContact distributed partitioned view


1. In the query window, type the following code to create the distributed partitioned view named Person.vContact on the AW_Contacts database:

USE AW_Contacts GO CREATE VIEW Person.vContact AS SELECT * FROM [NY-SQL-01].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE2].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE3].AW_Contacts.Person.Contact

2. 3. 4. 5. 6.

Examine this code. Execute the code. Examine the Messages box and verify that the script completed without any errors. Verify that the Person.vContact view is listed in the Object Explorer. Verify that the correct columns are listed in the view. Create a new query file. File name: ViewPersonContact.sql

7.

In the query window, type the following code to select the contents of the Person.vContact view:

USE AW_Contacts GO SELECT * FROM Person.vContact

8. 9.

Examine this code. Execute the code. Examine Messages box and verify that the script completed without any errors.

10. Verify that the result set of the Person.vContact view contains the data from the Person.Contact tables on all three SQL Server instances.
Results: After this exercise, you should have configured and tested a new partitioned view for the SQL Server.

Lab Instructions: Implementing Views

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Implementing Stored Procedures

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

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. 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, Type, Category, StartDate, EndDate, MinQty, and MaxQty. The procedure should return all rows sorted by StartDate and EndDate. Create a stored procedure named GetDiscountsForCategory within the Sales schema that accepts an input parameter named @Category, which is an nvarchar data type accepting up to 50 characters. The procedure should retrieve the same columns as for GetDiscounts, but should filter the rows based on the @Category parameter.

Lab Instructions: Implementing Stored Procedures

Create a stored procedure named GetDiscountsForCategoryAndDate within the Sales schema that accepts the @Category parameter as for GetDiscountsForCategory, but includes an additional @DateToCheck datetime input parameter. The @DateToCheck parameter must be able to accept a NULL default value. If a NULL value is specified for the @DateToCheck parameter, set the parameter value to the current date and time by using the GETDATE function. The procedure should retrieve the same columns as for GetDiscounts, but should filter the rows based on the @Category and @DateToCheck parameters. Create a stored procedure named AddDiscount within the Sales schema that inserts new records into the Sales.SpecialOffer table.

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. 4. Create and test the GetDiscounts stored procedure. Create and test the GetDiscountsForCategory stored procedure. Create and test the GetDiscountsForCategoryAndDate stored procedure. Create and test the AddDiscount stored procedure.

Task 1: Create and test the GetDiscounts stored procedure


1. 2. 3. Start 6232A-NY-SQL-01, and log on as Student with the password of Pa$$w0rd. Open the AWProgrammability.ssmssln solution in the E:\MOD07\Labfiles\Starter folder. Open the InitilizeData.sql query file, and then execute it, confirming that no errors occur. Always connect to the NY-SQL-01 SQL server when performing these tasks. 4. Create the Sales.GetDiscounts stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur. Create the stored procedure by executing the code under the --Create GetDiscount comment. Test the stored procedure by executing the code under the Test GetDiscounts comment.

Lab Instructions: Implementing Stored Procedures

Task 2: Create and test the GetDiscountsForCategory stored procedure


1. Create the Sales.GetDiscountForCategory stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur. Test the Sales.GetDiscountsForCategory stored procedure using 'Reseller' for the @Category value, and then review the results.

2.

Task 3: Create and test the GetDiscountsForCategoryAndDate stored procedure


1. Create the Sales.GetDiscountsForCategoryAndDate stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur. Test the Sales.GetDiscountsForCategoryAndDate stored procedure using 'Reseller' for the @Category value and the default value for the @DateToCheck parameter. Review the results. Test the Sales.GetDiscountForCategoryAndDate stored procedure using 'Reseller' for the @Category value and a date one month from now for the @DateToCheck value. Review the results.

2.

3.

Task 4: Create and test the AddDiscount stored procedure


1. Create the Sales.AddDiscount stored procedure according to the requirements, and then execute your CREATE PROCEDURE statement, confirming that no errors occur. Test 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' .5 'Seasonal Discount' 'Customer' Local variable with current date from GETDATE function Local variable with date one month from current date 0 20

2.

Lab Instructions: Implementing Stored Procedures

3. 4.

Confirm that a new special offer was create by displaying the @NewProductID OUTPUT parameter value. Copy the previous test, and change the @DiscountPct value to -0.5. Use the return value from the stored procedure to determine whether the insert succeeded or failed. If the insert failed, select the latest record from the dbo.ErrorLog table to confirm the error.

Results: After this exercise, you should have created and tested 4 stored procedures.

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. These queries are provided for you in the ExecutionPlans.sql query file in the AWProgrammability.ssmssln project. You must investigate the execution plans for the queries to identify problem areas. In this exercise, students will view text-based execution plans, graphical execution plans, tune the database to improve performance and view revised execution plans. The main tasks for this exercise are as follows: 1. 2. 3. 4. View text-based execution plans. View graphical execution plans. Tune the database to improve performance. View the revised execution plans.

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. 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.Product.Name column using the TransactSQL below the comment --Tune the database. Create an index on name.

Lab Instructions: Implementing Stored Procedures

Task 4: View the revised execution plan


Select and execute the code below the comment --retest the graphical execution plan. Observe the percentages involved in each operation of the query. Results: After this exercise, you should have created and viewed both text-based and graphical execution plans.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Implementing Functions

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

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

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.

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

Lab Instructions: Implementing Functions

14. Execute the statement below the comment Test Sales.GetMaximumDiscountForCategory as shown in the example below:
SELECT Sales.GetMaximumDiscountForCategory('Reseller')

15. Verify that a discount value is returned.

Task 2: Create and test the GetDiscountsForDate user-defined function


1. 2. In the UserDefinedFunctions.sql query locate the Create Sales.GetDiscountsForDate comment. Execute the CREATE FUNCTION statement as shown in the example below:

CREATE FUNCTION Sales.GetDiscountsForDate (@DateToCheck datetime) RETURNS TABLE AS RETURN ( SELECT Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty FROM Sales.SpecialOffer WHERE @DateToCheck BETWEEN StartDate AND EndDate )

3. 4.

Locate the Test Sales.GetDiscountsForDate comment. Test the function by executing the SELECT statement as show in the example below:

SELECT * FROM Sales.GetDiscountsForDate(GetDate()) ORDER BY DiscountPct DESC

5.

Verify that data is returned.

Lab Instructions: Implementing Functions

Task 3: Create and test the GetDiscountedProducts user-defined function


1. 2. In the UserDefinedFunctions.sql query locate the Create Sales.GetDiscountedProducts comment. Execute the CREATE FUNCTION statement as show in the example below.

CREATE FUNCTION Sales.GetDiscountedProducts (@IncludeHistory bit) RETURNS @tbl_products TABLE (ProductID int, Name nvarchar(50), ListPrice money, DiscountDescription nvarchar(255), DiscountPercentage smallmoney, DiscountAmount money, DiscountedPrice money) AS BEGIN IF (@IncludeHistory = 1) INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct 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) ORDER BY ProductID ELSE INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct

Lab Instructions: Implementing Functions

(continued)
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 FROM

3. 4.

Locate the Test Sales.GetDiscountedProducts comment. Test the function by executing the SELECT statements as shown in the example below.

SELECT * FROM Sales.GetDiscountedProducts(0) SELECT * FROM Sales.GetDiscountedProducts(1)

5.

Save UserDefinedFunctions.sql.

Results: After this exercise, you should have created and tested 3 user-defined functions.

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. 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 AdventureWorksDW database and must be accessed by using the NY-SQL01\Adam account. You must establish a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008 databases to enable the GetCurrencyRate function to retrieve the currency data. 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 the GetCurrencyRate user-defined function. Establish a database trust relationship between the AdventureWorks2008 database and the AdventureWorksDW2008 database. Create and test the GetCurrencyDiscountedProducts user-defined function.

Task 1: Create the GetCurrencyRate user-defined function


1. 2. 3. 4. In Solution Explorer open the query file ExecutionContext.sql. Connect to server NY-SQL-01 using Windows Authentication. Select and Execute the USE AdventureWorks2008 statement. Locate the Create Sales.GetCurrencyRate comment.

Lab Instructions: Implementing Functions

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.

12

Lab Instructions: Implementing Functions

7.

Test the function by execution the SELECT statement as shown in the following example:

SELECT * FROM Sales.GetCurrencyDiscountedProducts('GBP')

8. 9.

Review the query results and verify that the statement executes successfully. Save all open files and close Management Studio.

Results: After this exercise, you should have created two user-defined functions and created a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008..

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Implementing Managed Code in a Database

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

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.dll; you will only need to import, configure, and test the assembly. The AWorksUtilities.dll managed assembly is located in the E:\MOD09\Labfiles\Starter folder. 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

Lab Instructions: Implementing Managed Code in a Database

In this exercise you will import the custom assembly: AWorksUtilities. The main tasks for this exercise are as follows: 1. 2. Start the NY-SQL-01 virtual machine and log on as Administrator. Import the AWorksUtilities assembly.

Task 1: Start the NY-SQL-01 virtual machine and log on as Administrator


Start 6232A-NY-SQL-01, and log on as Administrator with the password of Pa$$w0rd.

Task 2: Import the AWorksUtilities assembly


1. 2. 3. 4. 5. Open the AWorks_CLR.ssmssln solution. Execute the Initialize.sql query file. Open the ImportAssembly.sql query file and add and run the code to enable CLR Integration. Add and run the code to create the AWorksUtilities assembly. Save the changed ImportAssembly.sql query file.
Results: After this exercise, you should have the managed database objects in the AWorksUtilities assembly available for use within the AdventureWorks2008 database.

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, the senior database developer has requested that you create links to and test the new managed database objects. The senior database developer has provided you with a SQL Server Scripts solution named AWorks_CLR.ssmssln in the E:\MOD09\Labfiles\Starter folder and the following requirements for the modifications you must make. The SaveXML stored procedure should accept one xml parameter named @XmlData and one nvarchar(100) parameter named @FileName. The external name of the managed stored procedure is AWorksUtilities.StoredProcedures.SaveXML. The GetLongDate user-defined function should accept one datetime parameter named @DateVal and should return an nvarchar(50) value. The external name of the managed function is AWorksUtilities.UserDefinedFunctions.GetLongDate. The EmailChange trigger should fire only on updates to the Person.EmailAddress table. The external name of the trigger is AWorksUtilities.Triggers.EmailChange. The Concatenate aggregate accepts one nvarchar(4000) parameter named @input and returns an nvarchar(4000) value. The external name of the aggregate is AWorksUtilities.Concatenate. The IPAddress user-defined type has the external name AWorksUtilities.IPAddress.

In this exercise you will test each of the new managed database objects. The main tasks for this exercise are as follows: 1. 2. 3. Create the SaveXML managed stored procedure referencing the external assembly. Create the GetLongDate managed user-defined function referencing the external assembly. Create the EmailChange managed trigger on the Person.EmailAddress table referencing the external assembly.

Lab Instructions: Implementing Managed Code in a Database

4. 5.

Create the Concatenate managed aggregate function referencing the external assembly. Create the IPAddress managed user-defined type referencing the external assembly.

Task 1: Create the SaveXML managed stored procedure referencing the external assembly
1. 2. 3. 4. 5. 6. 7. 8. 9. Open the SaveXML.sql query file and add the code to create the SaveXML stored procedure. Highlight and run the new code. Highlight and run the DECLARE, SET, and EXEC statements. Add code to change the security permissions. Highlight and run the ALTER ASSEMBLY statement. Highlight and run the DECLARE, SET, and EXEC statements. Save the SaveXML.sql file. Using Windows Explorer check for the existence of the Output.xml file in the E:\MOD09\Labfiles\Starter folder. Open the Output.xml file and verify that the file contains XML.

Task 2: Create the GetLongDate managed user-defined function referencing the external assembly
1. 2. 3. 4. 5. Open the GetLongDate.sql query file. Add the code to create the GetLongDate function then highlight and run the code. Select and run the SELECT statement and execute it. Confirm that the records returned display with a long OrderDate value. Save the GetLongDate.sql file.

Lab Instructions: Implementing Managed Code in a Database

Task 3: Create the EmailChange managed trigger on the Person.EmailAddress table referencing the external assembly
1. 2. 3. 4. 5. Open the EmailChange.sql query file. Add and execute the code to create the EmailChange trigger. Highlight and execute the first UPDATE statement Highlight and execute the second UPDATE statement. Save the EmailChange.sql file.

Task 4: Create the Concatenate managed aggregate function referencing the external assembly
1. 2. 3. 4. 5. Open the Concatenate.sql query file. Add and execute the code to create the Concatenate aggregate. Highlight and execute the SELECT statement. Confirm that orders are displayed as a concatenated string. Save the Concatenate.sql file.

Task 5: Create the IPAddress managed user-defined type referencing the external assembly
1. 2. 3. 4. 5. Open the IPAddress.sql query file. Add and execute the code to create the new IPAddress type Highlight and execute the SELECT statements. Confirm that three result sets are displayed that show the IPAddress value in various forms. Save the IPAddress.sql file.
Results: After this exercise, you should have successfully imported assembly code and created managed database objects.

Lab Instructions: Implementing Managed Code in a Database

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Managing Transactions and Locks

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

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. In order to avoid data integrity issues that are occurring, you need to enclose some of your business logic in transactions. You will work with simple queries to ensure that you understand the issues before you implement this in the live database.

Task 1: Start the virtual machine and log on as Student


1. 2. In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd.

Lab Instructions: Managing Transactions and Locks

Task 2: Create and commit a transaction


1. 2. 3. 4. 5. 6. 7. 8. 9. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Open the script E:\Mod10\Labfiles\Starter\Tran1.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the script. Add a statement to begin a transaction in the appropriate place. Execute the script. Notice that the transaction has not ended. Add a statement to commit the transaction in the appropriate place. Execute the statement that you have just added to end the transaction. Execute the last two statements of the script to verify that the changes have been committed to the database. Close the file.

Task 3: Create and rollback a transaction


1. 2. 3. 4. 5. Open the script E:\Mod10\Labfiles\Starter\Tran2.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the script. Add a statement to roll back the transaction in the appropriate place. Execute the script and verify that the changes are not made and the transaction is complete. Close SQL Server Management Studio.
Results: After this exercise, you should have committed and rolled back transactions.

Lab Instructions: Managing Transactions and Locks

Exercise 2: Managing Locks


Scenario
Now, you also need to solve some locking errors that are occurring in user applications, so you must test out some scenarios to identify and resolve the issues.

Task 1: View locking information


1. 2. 3. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Use the Activity Monitor window to review the current lock information. Create a new query to select the following columns from the sys.dm_tran_locks dynamic management view. 4. 5. 6. 7. 8. 9. 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. Open the script E:\Mod10\Labfiles\Starter\Lock1.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review and execute the script, noting the SPID of your connection. 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. In the Lock1 query window, execute a ROLLBACK TRANSACTION statement.

10. Execute the query against the sys.dm_tran_locks dynamic management view and note the new locks have been released.

Lab Instructions: Managing Transactions and Locks

Task 2: Set locking options


1. 2. 3. 4. 5. 6. 7. 8. Start SQL Server Management Studio and connect to the NY-SQL-01 instance by using Windows authentication. Open E:\Mod10\Labfiles\Starter\Lock1.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the contents of the file and execute the script. Open E:\Mod10\Labfiles\Starter\Lock2.sql and connect to the NY-SQL-01 instance by using Windows authentication. Review the contents of the file and execute the script. Open E:\Mod\10Labfiles\Starter\LockList.sql and connect to the NY-SQL01 instance by using Windows authentication. Execute the script and notice the WAIT entry in the request_status column. Cancel the Lock2.sql script and verify that the waiting transaction has been cancelled.

Task 3: Set the lock timeout


1. 2. 3. Add a SET statement to the start of the Lock2.sql script to change the lock timeout to five seconds. Execute the query and note that the query now times out. Close SQL Server Management Studio.
Results: After this exercise, you should have set locking options and set the lock timeout.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Instructions: Using Service Broker

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

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 companys Web site. To minimize the impact to the sites scalability, the senior database developer has decided to implement this functionality through a service that will be invoked asynchronously when a new user registers. 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.

Lab Instructions: Using Service Broker

When your work is complete, the senior database developer will modify the customer registration process to use the services you create. 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. The database administrator has provided a batch file named LabSetup.cmd to configure Database Mail on your development computer. You must enable Service Broker in the AdventureWorks database by using the ALTER DATABASE statement. To enable secure communication between services, you must also create a master key with a secure password in the AdventureWorks database. You must create schemas named EmailSvc and CustomerSvc in the AdventureWorks database, and then create a table named EmailLog in the EmailSvc schema. The EmailLog table should have the following definition.
CREATE TABLE EMailSvc.EmailLog ( Date datetime NOT NULL, [Event] nvarchar(50) NOT NULL, CustomerData xml )

Use the following details to create a message type that will be used to pass customer data to the EmailService service.
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.
Property Name Message type Message Direction Value //AW/EMail/SendCustomerDetails //AW/EMail/CustomerDetails SENT BY INITIATOR

Lab Instructions: Using Service Broker

Use the following details to create a queue that will be used by the CustomerService service.
Property Name Queue status Value CustomerSvc.NewCustomerQueue ON

Use the following details to create a queue that will be used by the EmailService service. The queue should initially be disabled until you create the stored procedure that the queue will activate.
Property Name Queue status Value EMailSvc.NewCustomerEmailQueue OFF

Use the following details to create the CustomerService service.


Property Name Queue Value //AW/Sales/CustomerService CustomerSvc.NewCustomerQueue

Use the following details to create the EmailService service.


Property Name Queue Contract Value //AW/EMail/EmailService EMailSvc.NewCustomerEmailQueue //AW/EMail/SendCustomerDetails

In this exercise, you will configure Database Mail, enable Service Broker in the AdventureWorks2008 database, and then create the message type, contract, queue and services required for the solution. The main tasks for this exercise are as follows: 1. 2. Launch SQL Server Management Studio. Create the AW_ServiceBroker SQL Server Scripts project.

Lab Instructions: Using Service Broker

3. 4.

Configure the AdventureWorks database for Service Broker. Create the Service Broker objects required for the customer e-mail solution.

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.

Task 2: Create the AW_ServiceBroker SQL Server Scripts project


1. 2. Open SQL Server Management Studio and connect to the default database engine. Create a new project named AW_ServiceBroker in the E:\MOD11\Labfiles\Starter folder.

Task 3: Configure the AdventureWorks database for Service Broker


1. 2. Create a new query named PrepareDatabase.sql in the AdventureWorks2008 database. In the PrepareDatabase.sql query you should enable Service Broker, create a master key encryption with the password 23987hxJ#KL95234nl0zBe, create a schema named EMailSvc, create another schema named CustomerSvc, create a table to log details of the customer e-mails sent, and set the database to multi-user mode.

Task 4: Create the Service Broker objects required for the customer email solution
1. 2. Create a new query named CreateServiceBrokerObjects.sql in the AdventureWorks2008 database. In the CreateServiceBrokerObjects.sql query you should create message types, create contracts, create queues, and create services based on the information provided in the scenario section of this exercise.

Lab Instructions: Using Service Broker

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

Lab Instructions: Using Service Broker

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. The senior database developer has provided Transact-SQL scripts to create the CustomerSvc.uspEmailNewCustomer stored procedure used by the services. In this exercise, you will add an existing query file to the project and execute the code in it. This code creates a stored procedure that sends messages from the CustomerService service to the EmailService service. The main tasks for this exercise are as follows: 1 2. Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker project. Implement the CustomerService service.

Task 1: Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker project


1. 2. Use the Add Existing Item option to add an item to the project. Add the CreateEmailNewCustomerSP.sql query file in the E:\MOD11\Labfiles\Starter folder to the project.

Task 2: Implement the CustomerService service


1. 2. Execute the CreateEmailNewCustomerSP.sql query. Verify that the CustomerSvc.uspEmailNewCustomer stored procedure is listed under the Stored Procedures list of the AdventureWorks2008 database.
Results: After this exercise, you should have created the CustomerSvc.uspEmailNewCustomer stored procedure used by the service.

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. The senior database developer has provided TransactSQL scripts to create the EMailSvc.uspSendCustomerEmail stored procedure used by the services. After you have created the EMailSvc.uspSendCustomerEmail stored procedure, you must alter the queue used by the EmailService service to make it activate the EMailSvc.uspSendCustomerEmail stored procedure whenever a message is received. Use the following settings.
Property Name Queue status Activation status Procedure name Maximum readers Execute as Value EMailSvc.NewCustomerEmailQueue ON ON AdventureWorks.EMailSvc.uspSendCustomerEmail 5 OWNER

In this exercise, you will add an existing query file to the project and execute the code it contains. This code creates a stored procedure that receives and processes messages in the EmailService service. The main tasks for this exercise are as follows: 1. 2. 3. 4. Add the CreateSendEmailSP.sql query file to the AW_ServiceBroker project. Implement the EmailService service. Configure the target service for automatic activation. Test the EmailService service.

Lab Instructions: Using Service Broker

Task 1: Add the CreateSendEmailSP.sql query file to the AW_ServiceBroker project


1. 2. Use the Add Existing Item option to add an item to the project. Add the CreateSendEmailSP.sql query file in the E:\MOD11\Labfiles\Starter folder to the project.

Task 2: Implement the EmailService service


1. 2. Execute the CreateSendEmailSP.sql query. Verify that the EMailSvc.uspSendCustomerEmail stored procedure is listed under the Stored Procedures list of the AdventureWorks2008 database.

Task 3: Configure the target service for automatic activation


1. 2. Create a new query named AlterServiceBrokerQueue.sql. In the query window, write a T-SQL statement to make the EMailSvc.NewCustomerEmailQueue queue activate the EMailSvc.uspSendCustomerEmail stored procedure using the settings provided in the scenario. Execute the query.

3.

Task 4: Test the EmailService service


1. 2. 3. Use the Add Existing Item option to add an item to the project. Add the TestEmailService.sql query file in the E:\MOD11\Labfiles\Starter folder to the project. Execute the query.
Results: After this exercise, you should have created a stored procedure that receives and processes messages in the EmailService service. You should have also tested the EmailService service.

Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.

Lab Answer Key: Creating Databases and Database Files

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

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. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, verify that Server type is set to Database Engine and Server name is set to NY-SQL-01, and then click Connect. Maximize Microsoft SQL Server Management Studio. In Object Explorer expand NY-SQL-01, right-click Databases, and then click New Database. The New Database window appears. Maximize the window. On the General page, in the Database name field, enter AW_IT_Assets. In the Database files pane, click the AW_IT_Assets logical name, enter AW_IT_Assets_Data1, and then press ENTER.

10. Click Add. A new database file is added to the Database files pane. 11. Click the logical name cell of the new database file, enter AW_IT_Assets_Data2, and then press ENTER. 12. Click the cell labeled PRIMARY at the intersection of the AW_IT_Assets_Data2 row and the Filegroup column, and then select <new filegroup> from the drop-down menu. 13. The New Filegroup for AW_IT_Assets dialog box appears. Enter SECONDARY in the Name field, select Default, and then click OK. 14. Enter 20 in the Initial Size column of the AW_IT_Assets_Data1 row.

Lab Answer Key: Creating Databases and Database Files

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

Lab Answer Key: Creating Databases and Database Files

Task 2: Create a new database by executing a SQL Server Management Studio Scripts project
1. 2. 3. In Microsoft SQL Server Management Studio, click File, point to Open, and then click File. The Open File dialog box appears. Browse to E:\MOD01\Labfiles, select AW_IT_Assets_DBScript, and then click Open. Click Execute on the SQL Editor toolbar.

Note: The query may take several minutes to execute successfully. Once the status bar at the bottom of the query window displays FileGroup Property default has been set, move on to step 4.

4. 5. 6. 7.

Right-click NY-SQL-01 | Databases in Object Explorer and then click Refresh. Expand NY-SQL-01 | Databases. The AW_IT_Assets database has been added to the Databases folder. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created a new database with the appropriate options and filegroups and created a SQL Server Management Studio Scripts project.

Exercise 2: Creating a Schema


Task 1: Create a new database user
1. 2. In SQL Server Management Studio expand NY-SQL-01 | Databases | AW_IT_Assets | Security, right-click Users, and then click New User. In the Database User New window, enter Katie in the User name field and NY-SQL-01\Katie in the Login name field, and then click OK.

Lab Answer Key: Creating Databases and Database Files

Task 2: Create a schema and assign ownership to a user


1. 2. Click New Query on the Standard toolbar. In the new, blank query window, type the following T-SQL statement:
CREATE SCHEMA TechSupport AUTHORIZATION Katie CREATE TABLE Hardware (source int, cost int, partnumber int) GRANT SELECT TO Katie; GO

3. 4.

On the toolbar, click Execute. Close the query editor without saving the query.

Task 3: Create a schema and assign ownership to a user


1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE SCHEMA_NAME = 'TechSupport'; GO

3. 4. 5.

On the toolbar, click Execute. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created a schema and assigned ownership to a user. You should have also displayed ownership of the newly created schema.

Lab Answer Key: Creating Databases and Database Files

Exercise 3: Creating a Database Snapshot


Task 1: Create a database snapshot
1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE DATABASE AW_IT_Assets_Snapshot1 ON ( NAME = AW_IT_Assets_Data1, FILENAME = 'E:\MOD01\Labfiles\Snapshots\AW_IT_Assets_Data1.ss' ), ( NAME = AW_IT_Assets_Data2, FILENAME = E:\MOD01\Labfiles\Snapshots\AW_IT_Assets_Data2.ss ) AS SNAPSHOT OF AW_IT_Assets; GO

3. 4. 5. 6.

On the toolbar, click Execute. Close the query editor without saving the query. In Object Explorer, right-click NY-SQL-01 | Databases, and then click Refresh. Expand NY-SQL-01 | Databases | Database Snapshots and review the new database snapshot named AW_IT_Assets_Snapshot1.

Task 2: Alter the database


1. 2. 3. 4. Expand NY-SQL-01 | Databases | AW_IT_Assets | Tables, right-click the TechSupport.Hardware table, and then click Delete. The Delete Object window appears. Click OK. Expand NY-SQL-01 | Databases | AW_IT_Assets | Security | Schemas, right-click the TechSupport schema, and then click Delete. The Delete Object window appears. Click OK.

Lab Answer Key: Creating Databases and Database Files

Task 3: Revert the database to the previously created database snapshot


1. 2. In Object Explorer, expand NY-SQL-01 | Databases, right-click the AW_IT_Assets database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
USE master; RESTORE DATABASE AW_IT_Assets FROM DATABASE_SNAPSHOT = AW_IT_Assets_Snapshot1'; GO

3. 4. 5.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases, and then click Refresh. 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.Hardware table and the TechSupport schema have been restored. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes.
Results: After this exercise, you should have created a database snapshot, altered the database, and then reverted the database to the database snapshot.

6.

Lab Answer Key: Creating Data Types and Tables

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

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. 2. 3. 4. 5. 6. 7. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, verify that Server type is set to Database Engine and Server name is set to NY-SQL-01, and then click Connect. Maximize Microsoft SQL Server Management Studio. Expand NY-SQL-01 | Databases, right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TYPE ShortDescription FROM nvarchar(10) NOT NULL;

8. 9.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Programmability | Types | User-Defined Data Types, click Refresh, and then expand User-Defined Data Types to view the new dbo.ShortDescription data type.

10. Close the query editor without saving the query.

Lab Answer Key: Creating Data Types and Tables

Task 2: Create a data type based on the decimal system-supplied data type
1. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TYPE CashValue FROM decimal(8,2) NOT NULL;

3. 4.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Programmability | Types | User-Defined Data Types, click Refresh, and then expand User-Defined Data Types to view the new dbo.CashValue data type. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have successfully created a new data type based on the nvarchar system-supplied data type. You should have also successfully created a new data type based on the decimal system-supplied data type.

5. 6.

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. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
SELECT CAST('2007-05-08 12:35:29.1234567 'time' ,CAST('2007-05-08 12:35:29.1234567 ,CAST('2007-05-08 12:35:29.123' AS 'smalldatetime' ,CAST('2007-05-08 12:35:29.123' AS ,CAST('2007-05-08 12:35:29.1234567 'datetime2' ,CAST('2007-05-08 12:35:29.1234567 datetimeoffset(7)) AS 'datetimeoffset'; +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. 4.

On the toolbar, click Execute and then review the results. Close the query editor without saving the query.

Task 2: Convert sample data into new data type formats using T-SQL
1. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
SELECT '2006-04-04T15:50:59.997' AS UnconvertedText, CAST('2006-04-04T15:50:59.997' AS datetime) AS UsingCast, CONVERT(date, '2006-04-04T15:50:59.997', 126) AS UsingConvertDate, CONVERT(time, 2006-04-04T15:50:59.997', 126) AS UsingConvertTime; GO

Lab Answer Key: Creating Data Types and Tables

3. 4. 5.

On the toolbar, click Execute and then review the results. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, 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.

Exercise 3: Creating Tables


Task 1: Create a table named ReturnedGoods
1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TABLE ReturnedGoods ( ReturnID int identity, ProductID int, CustomerID int, ReturnDate datetime, ReturnReason ShortDescription NULL ); GO

3. 4.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables, click Refresh, and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new ReturnedGoods table. Close the query editor without saving the query.

5.

Task 2: Create a table named Refunds


1. 2. Right-click the AdventureWorksDW2008 database, and then click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE TABLE Refunds ( RefundID int identity, ReturnID int, Amount CashValue ); GO

3.

On the toolbar, click Execute.

Lab Answer Key: Creating Data Types and Tables

4.

Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables, click Refresh, and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new Refunds table. Close the query editor without saving the query. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created a table named ReturnedGoods, created a table named Refunds, and followed all provided specifications.

5. 6.

Exercise 4: Creating Partitioned Tables


Task 1: Limit result sets by using the INTERSECT clause with the SELECT statement
1. 2. 3. 4. On the SQL Server Management Studio toolbar, click File, point to Open, and then click File. Browse to E:\MOD02\Labfiles\Scripts, select the file named partition_prep.sql, and then click Open. On the toolbar, click Execute. Close the query editor without saving the query.

Lab Answer Key: Creating Data Types and Tables

Task 2: Create a partitioned table named ReturnsArchive


1. 2. In SQL Server Management Studio, on the toolbar, click New Query. In the new, blank query window, type the following T-SQL statement:
CREATE PARTITION FUNCTION myRangePF1 (int) AS RANGE LEFT FOR VALUES (1, 100, 1000); GO CREATE PARTITION SCHEME myRangePS1 AS PARTITION myRangePF1 TO (Test1FG, Test2FG, Test3FG, Test4FG); GO CREATE TABLE ReturnsArchive (ReturnID int identity, ProductID int, CustomerID int, ReturnDate datetime, ReturnReason ShortDescription NULL ) ON myRangePS1 (ReturnID); GO

3. 4.

On the toolbar, click Execute. Right-click NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables, click Refresh, and then expand NY-SQL-01 | Databases | AdventureWorksDW2008 | Tables to view the new ReturnsArchive table. Close the query editor without saving the query.

5.

Task 3: Review the partitioning implementation


1. 2. 3. 4. 5. In Object Explorer, right-click the AdventureWorksDW2008 database, and then click Refresh. Expand NY-SQL-01 | AdventureWorksDW2008 | Tables, right-click the dbo.ReturnsArchive table, and then click Properties. In the Table Properties window, click Storage on the left. Review the Compression, Filegroups, and Partitioning information in the right pane of the Table Properties window, and then click OK. Turn off the 6232A-NY-SQL-01 virtual machine and discard any changes.
Results: After this exercise, you should have successfully prepared the database for partitioning, created a partitioned table named ReturnsArchive according to the specifications provided, and then reviewed the partitioning changes.

Lab Answer Key: Creating and Tuning Indexes

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

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 Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Student with the password of Pa$$w0rd.

Task 2: Create a SQL Server Scripts project


1. 2. 3. 4. 5. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, click Connect. On the File menu, click New, and then click Project. In the New Project dialog box, in the Name field, type AW_Indexes. Change the Location field to E:\MOD03\Labfiles\Starter. Clear the Create directory for solution check box, and then click OK.

Lab Answer Key: Creating and Tuning Indexes

Task 3: Create the Ix_Product_Supply_Chain index


1. 2. 3. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type CreateIndex.sql, and then press ENTER. In the query window, 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.Product (ProductNumber, Color, ReorderPoint, SafetyStockLevel) INCLUDE (DaysToManufacture) WITH (ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = OFF, FILLFACTOR = 90, PAD_INDEX = ON)

4. 5. 6. 7. 8. 9.

On the toolbar, click Execute. On the File menu, click Save All. If Object Explorer is not visible, on the View menu, click Object Explorer. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Tables. Expand Production.Product, expand Indexes, and then verify that the Ix_Product_Supply_Chain index is listed. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have successfully created a SQL Server Scripts project and created the Ix_Product_Supply_Chain index.

Lab Answer Key: Creating and Tuning Indexes

Exercise 2: Optimizing Indexes


Task 1: Add the sample products to the database
1. 2. 3. 4. In Microsoft SQL Server Management Studio, on the File menu, click Open, and then click File. In the Open File dialog box, browse to the E:\MOD03\Labfiles\Starter folder, click the aw2008sampleproductadd.sql file, and then click Open. In Microsoft SQL Server Management Studio, on the toolbar, click Execute. Wait for the query to finish executing before continuing to the next task. Note that there may be some duplicate key errors. You can ignore this.

Task 2: Reorganize AK_Product_ProductNumber


1. 2. 3. 4. 5. 6. 7. 8. 9. In Object Explorer, make sure that Databases | AdventureWorks2008 | Tables | Production.Product | Indexes is still expanded. Right-click AK_Product_ProductNumber (Unique, Non-Clustered), and then click Properties. In the Index Properties AK_Product_ProductNumber dialog box, in the Select a page pane, click Fragmentation. In the details pane, under Fragmentation, notice that Total Fragmentation is 66.67%. Click Cancel. In Object Explorer, right-click AK_Product_ProductNumber (Unique, NonClustered), and then click Reorganize. In the Reorganize Indexes dialog box, click OK. In Object Explorer, right-click AK_Product_ProductNumber (Unique, NonClustered), and then click Properties. In the Index Properties AK_Product_ProductNumber dialog box, in the Select a page pane, click Fragmentation.

10. In the details pane, notice that Total fragmentation has changed to 50.00%. 11. Click Cancel.

Lab Answer Key: Creating and Tuning Indexes

Task 3: Rebuild AK_Product_Name


1. 2. 3. 4. 5. 6. 7. 8. 9. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Properties. In the Index Properties AK_Product_Name dialog box, in the Select a page pane, click Fragmentation. In the details pane, notice that Total fragmentation is 80.00%. Click Cancel. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Rebuild. In the Rebuild Indexes dialog box, click OK. In Object Explorer, right-click AK_Product_Name (Unique, Non-Clustered), and then click Properties. In the Index Properties AK_Product_Name dialog box, in the Select a page pane, click Fragmentation. In the details pane, notice that Total fragmentation is now 25.00%.

10. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab.
Results: After this exercise, you should have successfully optimized the Production.Product table indexes using both reorganize and rebuild.

Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers

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

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. 2. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Student with the password of Pa$$w0rd.

Task 2: Create a SQL Server Scripts project


1. 2. 3. 4. 5. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, click Connect. On the File menu, click New, and then click Project. In the New Project dialog box, in the Name field, type AW_DataIntegrity. Change the Location field to E:\MOD04\Labfiles\Starter. Clear the Create directory for solution check box, and then click OK.

Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers

Task 3: Create the JobCandidateHistory table and constraints


1. 2. 3. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type TableAndContraints.sql, and then press ENTER. In the query window, type the following Transact-SQL code to create the JobCandidateHistory table:
USE [AdventureWorks2008] GO CREATE TABLE [HumanResources].[JobCandidateHistory]( [JobCandidateID] [int] NOT NULL UNIQUE, [Rating] [int] NOT NULL CONSTRAINT [DF_JobCandidateHistory_Rating] Default (5), [RejectedDate] [datetime] NOT NULL, [BusinessEntityID] [int] NULL, CONSTRAINT [FK_JobCandidateHistory_BusinessEntity_BusinessEntityID] FOREIGN KEY (BusinessEntityID) REFERENCES [Person].[BusinessEntity] (BusinessEntityID), CONSTRAINT [CK_JobCandidateHistory_Rating] CHECK ([Rating]>=0 AND [Rating]<=10) ) ON [PRIMARY]

4. 5. 6. 7.

On the toolbar, click Execute. On the File menu, click Save All. If Object Explorer is not visible, on the View menu, click Object Explorer. In Object Explorer, expand Databases, expand AdventureWorks2008, expand Tables, and then verify that the HumanResources.JobCandidateHistory table is listed. You may need to rightclick Tables, and then click Refresh to see the new table. In Object Explorer, expand the HumanResources.JobCandidateHistory table. In the HumanResources.JobCandidateHistory table, expand the Columns, Keys, Indexes, and Constraints folders, and then verify that the necessary constraints have been implemented.

8. 9.

Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers

Task 4: Test the JobCandidateHistory table and constraints


1. 2. 3. In SQL Server Management Studio, on the File menu, click Open, and then click File. In the Open File dialog box, browse to E:\MOD04\Labfiles\Starter, click TestConstraints.sql, and then click Open. Below the comment This should fail, select the code, and then on the toolbar, click Execute. The INSERT operation should fail, because the Rating value conflicts with the CHECK constraint. Below the comment This should succeed, select the code, and then on the toolbar, click Execute. The INSERT operation should succeed. Keep SQL Server Management Studio open to use in the next exercise.
Results: After this exercise, you should have successfully created a SQL Server Scripts project, created the HumanResources.JobCandidateHistory table, and tested the constraints.

4. 5.

Exercise 2: Disabling Constraints


Task 1: Insert multiple rows into the JobCandidateHistory table
1. 2. 3. 4. In Microsoft SQL Server Management Studio, on the File menu, click Open, and then click File. In the Open File dialog box, browse to the E:\MOD04\Labfiles\Starter folder, click the InsertTestData.sql file, and then click Open. On the toolbar, click the Include Client Statistics button, and then click Execute. Click the Client Statistics tab, and verify that the Time Statistics have been recorded.

Task 2: Disable constraints on the JobCandidateHistory table


1. 2. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type Constraints.sql, and then press ENTER.

Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers

3.

In the query window, type the following Transact-SQL code:


USE [AdventureWorks2008] GO ALTER TABLE HumanResources.JobCandidateHistory NOCHECK CONSTRAINT [CK_JobCandidateHistory_Rating] GO

4. 5. 6. 7. 8. 9.

On the toolbar, click Execute. Verify that the commands completed successfully. On the File menu, click Save All. Switch to the InsertTestData.sql query window. On the toolbar, click Execute. Click the Client Statistics tab, and then compare the Time Statistics with the previous trial. Notice that Trial 2 executes more quickly.

Task 3: Enable constraints on the JobCandidateHistory table


1. 2. Switch to the Constraints.sql query window. In the query window, type the following Transact-SQL code below the existing statements:
ALTER TABLE HumanResources.JobCandidateHistory CHECK CONSTRAINT [CK_JobCandidateHistory_Rating] GO

3. 4. 5. 6.

Select the new statements, and then on the toolbar, click Execute. Verify that the commands completed successfully. On the File menu, click Save All. Keep SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have successfully compared performance results with constraints enabled and disabled.

Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers

Exercise 3: Creating Triggers


Task 1: Create the dJobCandidate trigger
1. 2. 3. In SQL Server Management Studio, on the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type Trigger.sql, and then press ENTER. In the query window, type the following Transact-SQL code to create the dJobCandidate trigger on the HumanResources.JobCandidate table:
USE AdventureWorks2008 GO CREATE TRIGGER [dJobCandidate] ON [HumanResources].[JobCandidate] AFTER DELETE AS BEGIN SET NOCOUNT ON; INSERT INTO [HumanResources].[JobCandidateHistory] (JobCandidateID, RejectedDate) SELECT JobCandidateID, getdate() FROM deleted END;

4. 5. 6. 7.

On the toolbar, click Execute. On the File menu, click Save All. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Tables. Right-click Tables, and then click Refresh. Expand the HumanResources.JobCandidate table, expand Triggers, and then verify that the dJobCandidate trigger is listed.

Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers

Task 2: Test the dJobCandidate trigger


1. 2. 3. 4. On the File menu, click Open, and then click File. In the Open File dialog box, browse to the E:\MOD04\Labfiles\Starter folder, click the TestTrigger.sql query file, and then click Open. On the toolbar, click Execute to execute the query script. In the results pane, verify that the record deleted from the HumanResources.JobCandidate table is inserted into the HumanResources.JobCandidateHistory table. The record should contain the default value of 5 for Rating, and the current date for RejectedDate. Click the Messages tab, 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. Close SQL Server Management Studio, and then shutdown the virtual machine without saving changes to reset it for the next Lab.
Results: After this exercise, you should have successfully created and tested the dJobCandidate trigger.

5.

6.

Lab Answer Key: Using XML

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

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. 2. 3. 4. 5. 6. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio. If the Connect to Server dialog box appears, click Connect. On the File menu, point to Open, and then click Project/Solution. The Open Project dialog box appears. Browse to the E:\Mod05\Labfiles\Starter folder, click the XML.ssmssln solution, and then click Open. a. b. c. 7. 8. 9. If the Connect to Server dialog box appears, click Connect. If Solution Explorer is not visible, on the View menu, click Solution Explorer. If necessary, in the Solution Explorer pane, expand XML | Queries.

In the Solution Explorer, double-click the FORXML.sql query to open it. Switch to the FORXML query. Examine the query and note that it retrieves data from the Sales.SalesOrderHeader and Sales.SalesOrderDetail tables in the AdventureWorks2008 database.

10. On the toolbar, click Execute. 11. Examine the Results and Messages boxes and verify that the script completed without any errors.

Lab Answer Key: Using XML

12. Modify the SELECT statement to include the FOR XML clause and return attribute-centric XML by using AUTO mode, as shown in the following Transact-SQL example:
SELECT SalesOrder.SalesOrderID, SalesOrder.OrderDate, SalesOrder.AccountNumber, Item.ProductID, Item.OrderQty FROM Sales.SalesOrderHeader SalesOrder JOIN Sales.SalesOrderDetail Item ON SalesOrder.SalesOrderID = Item.SalesOrderID WHERE SalesOrder.SalesOrderID = 43659 FOR XML AUTO

13. On the toolbar, click Execute. 14. Examine the Results and Messages boxes and verify that the script completed without any errors. 15. Review the query results. 16. In the query results, click the returned XML to view it in the XML editor. 17. 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" /> <!-- more items here --> </SalesOrder>

18. On the File menu, click Close to close the XML editor.

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

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)

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.

Lab Answer Key: Using XML

Task 2: Create the HumanResources.JobCandidateHistory table


1. 2. 3. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. In the query pane, type the following Transact-SQL code to create a table named HumanResources.JobCandidateHistory in the AdventureWorks2008 database:
USE AdventureWorks2008 GO CREATE TABLE HumanResources.JobCandidateHistory ( JobCandidateID int IDENTITY PRIMARY KEY, BusinessEntityID int NULL, Rating int NOT NULL Default (5), RejectedDate datetime NOT NULL, NationalIDNumber nvarchar (15) NOT NULL, ModifiedDate DateTime, Resume xml ) GO

4. 5. 6. 7. 8. 9.

On the toolbar, click Execute. If the Connect to Server dialog box appears, click Connect. Examine Messages box and verify that the script completed without any errors. On the File menu, click Save SQLQuery1.sql As. The Save File As dialog box appears. In the File name field, type CreateJobCandidateHistoryTable.sql, and then click Save. In Object Explorer, expand Databases | AdventureWorks2008 | Tables.

10. Verify that the HumanResources.JobCandidateHistory table is listed. 11. In Object Explorer, expand the HumanResources.JobCandidateHistory table. 12. In the HumanResources.JobCandidateHistory table, expand Columns. 13. Verify that the necessary columns have been successfully created.

Lab Answer Key: Using XML

Task 3: Create a new query file


1. 2. 3. 4. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery2.sql As. The Save File As dialog box appears. In the File name field, type XMLSchema.sql, and then click Save.

Task 4: Create an XML schema collection named HumanResources.HistoricResumeSchemaCollection


1. 2. 3. 4. 5. 6. 7. 8. 9. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click XML Files. Navigate to the E:\Mod05\Labfiles\Starter folder. Click HistoricResumeSchema.xml, and then click Add. In the details pane, examine the new schema definition. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, click SQL Server files. Navigate to the E:\Mod05\Labfiles\Starter folder. Click CreateXMLSchema.sql, and then click Add.

10. If the Connect to Server dialog box appears, click Connect.

Lab Answer Key: Using XML

11. Examine the code that creates the new XML Schema. It should be identical to the code listed below:
USE AdventureWorks2008 GO CREATE XML SCHEMA COLLECTION HumanResources.HistoricResumeSchemaCollection AS N'<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:t="http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume" targetNamespace="http://schemas.microsoft.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.Type" type="xsd:string" /> <xsd:element name="Addr.OrgName" type="xsd:string" /> <xsd:element name="Addr.Street" type="xsd:string" maxOccurs="unbounded" /> <xsd:element name="Addr.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.PostalCode" type="xsd:string" /> <xsd:element name="Addr.Telephone" minOccurs="0"> <xsd:complexType> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence>

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.StartDate" type="xsd:date" /> <xsd:element name="Edu.EndDate" type="xsd:date" /> <xsd:element name="Edu.Degree" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.Major" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.Minor" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.GPA" type="xsd:string" minOccurs="0" /> <xsd:element name="Edu.GPAAlternate" type="xsd:decimal" minOccurs="0" /> <xsd:element name="Edu.GPAScale" type="xsd:decimal" minOccurs="0" /> <xsd:element name="Edu.School" type="xsd:string" 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>

Lab Answer Key: Using XML

11

(continued)
<xsd:complexType name="EmploymentType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Emp.StartDate" type="xsd:date" minOccurs="0" /> <xsd:element name="Emp.EndDate" type="xsd:date" minOccurs="0" /> <xsd:element name="Emp.OrgName" type="xsd:string" /> <xsd:element name="Emp.JobTitle" type="xsd:string" /> <xsd:element name="Emp.Responsibility" type="xsd:string" /> <xsd:element name="Emp.FunctionCategory" type="xsd:string" minOccurs="0" /> <xsd:element name="Emp.IndustryCategory" type="xsd:string" minOccurs="0" /> <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.CountryRegion" type="xsd:string" /> <xsd:element name="Loc.State" type="xsd:string" minOccurs="0" /> <xsd:element name="Loc.City" type="xsd:string" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType>

12

Lab Answer Key: Using XML

(continued)
<xsd:complexType name="NameType"> <xsd:complexContent> <xsd:restriction base="xsd:anyType"> <xsd:sequence> <xsd:element name="Name.Prefix" type="xsd:string" minOccurs="0" /> <xsd:element name="Name.First" type="xsd:string" /> <xsd:element name="Name.Middle" type="xsd:string" minOccurs="0" /> <xsd:element name="Name.Last" type="xsd:string" /> <xsd:element name="Name.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.IntlCode" type="xsd:int" minOccurs="0" /> <xsd:element name="Tel.AreaCode" type="xsd:int" minOccurs="0" /> <xsd:element name="Tel.Number" type="xsd:string" />

Lab Answer Key: Using XML

13

(continued)
<xsd:element name="Tel.Extension" type="xsd:int" minOccurs="0" /> </xsd:sequence> </xsd:restriction> </xsd:complexContent> </xsd:complexType> </xsd:schema>' GO

12. On the toolbar, click Execute. 13. Examine Messages box and verify that the script completed without any errors.

Task 5: Apply the schema collection to the JobCandidateHistory.Resume column


1. 2. 3. 4. 5. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery3.sql As. The Save File As dialog box appears. In the File name field, type AlterCandidateTable.sql, and then click Save. In the query window, enter the following code to alter the JobCandidateHistory table:
ALTER TABLE HumanResources.JobCandidateHistory ALTER COLUMN Resume xml (HumanResources.HistoricResumeSchemaCollection) GO

6. 7. 8. 9.

On the toolbar, click Execute. Examine Messages box and verify that the script completed without any errors. In Object Explorer, right-click AdventureWorks2008, and then click Refresh. In Object Explorer, ensure that Databases | AdventureWorks2008 are expanded, expand Tables, expand HumanResources.JobCandidateHistory, and then expand Columns.

14

Lab Answer Key: Using XML

10. Notice that the Resume column is now associated with the HumanResources.HistoricResumeSchemaCollection.

Lab Answer Key: Using XML

15

Task 6: Test the HistoricResumeSchema XML schema


1. 2. 3. 4. 5. 6. 7. 8. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, ensure that SQL Server files is selected. Navigate to the E:\Mod05\Labfiles\Starter folder. Click TestXMLSchema.sql, and then click Add. If the Connect to Server dialog box appears, click Connect. In the details pane, below the comment This should fail, select the INSERT code. On the toolbar, click Execute. Examine the error message in the Messages pane. The INSERT operation fails because the Resume XML does not conform to the schema. 9. Below the comment This should succeed, select the code.

10. On the toolbar, click Execute. 11. Examine the Message box and verify that the script completed without any errors. The INSERT operation should succeed. 12. In the Solution Explorer pane, right-click Queries, and then click New Query. 13. If the Connect to Server dialog box appears, click Connect. 14. On the File menu, click Save SQLQuery4.sql As. 15. The Save File As dialog box appears. In the File name field, type SelectCandidates.sql, and then click Save.

16

Lab Answer Key: Using XML

16. Type the following Transact-SQL code:


USE AdventureWorks2008 GO SELECT * FROM HumanResources.JobCandidateHistory GO

17. On the toolbar, click Execute. 18. Examine the Results and Messages boxes and verify that the script completed without any errors. 19. In the Results pane, in the first row, click the <Resume> field. 20. Examine the XML record to confirm that it is complete and accurate. 21. On the File menu, click Close to close the XML editor.

Task 7: Populate the HumanResources.JobCandidateHistory table with additional sample data


1. 2. 3. 4. 5. 6. 7. 8. 9. In the Solution Explorer, right-click Job Candidate History, point to Add, and then click Existing item. The Add Existing Item - Job Candidate History dialog box appears. In the File of type list, ensure that SQL Server files is selected. Navigate to the E:\Mod05\Labfiles\Starter folder. Click AddCandidate.sql, and then click Add. If the Connect to Server dialog box appears, click Connect. On the toolbar, click Execute. Examine the Message box and verify that the script completed without any errors. In the Solution Explorer, double-click SelectCandidates.sql. On the toolbar, click Execute.

10. Examine the Results and Messages boxes and verify that the script completed without any errors. 11. In the Results pane, in the second row, click the <Resume> field. 12. Examine the xml record to confirm that it is accurate. 13. On the File menu, click Close to close the XML editor.

Lab Answer Key: Using XML

17

14. On the File menu, click Save All. 15. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.

Note: This is the end of the first part of the module and the remaining exercises will come after the rest of the presentation.

Results: After this exercise, the student has created and applied an XML schema and stored XML natively in the database.

Exercise 3: Using XQuery with XML Methods


Task 1: Retrieve the resume elements
1. 2. 3. 4. 5. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery5.sql As. The Save File As dialog box appears. In the File name field, type xmlMethods.sql, and then click Save. In the query window, enter the following code to retrieve the resume elements:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT NationalIDNumber, Resume.query(' /RES:Resume/RES:Name ') as Result FROM HumanResources.JobCandidateHistory GO

6. 7. 8.

On the toolbar, click Execute. Examine the Results and Messages boxes and verify that the script completed without any errors. Verify that the desired results are returned.

18

Lab Answer Key: Using XML

Task 2: Retrieve the address for a specified candidate


1. Below the SELECT statement, type the following Transact-SQL code:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") SELECT Resume.value( '(/RES:Resume/RES:Address/RES:Addr.Street)[1]', 'nvarchar(100)') As ResumeAddress FROM HumanResources.JobCandidateHistory WHERE JobCandidateID = 2 GO

This retrieves a single resume address with a JobCandidateID of 2. 2. 3. Select the statements you just added, and then on the toolbar, click Execute. Verify that the desired results are returned.

Task 3: Update a candidate's address


1. Below the previous SELECT statement, type the following Transact-SQL code:
USE AdventureWorks2008 GO WITH XMLNAMESPACES( 'http://schemas.microsoft.com/sqlserver/2004/07/adventureworks/Resume' AS "RES") UPDATE HumanResources.JobCandidateHistory SET Resume.modify('replace value of (/RES:Resume/RES:Address/RES:Addr.Street)[1] with "7194 Fourth St. Rockhampton"') WHERE JobCandidateID = 2 GO

2.

This updates the HumanResources.JobCandidateHistory table, setting the Address element value in the document for the record with a JobCandidateID of 2 to 7194 Fourth St. Rockhampton.

Lab Answer Key: Using XML

19

3. 4.

Select the statements you just added, and then on the toolbar, click the Execute button. Examine the Messages box and verify that the script completed without any errors.

Task 4: Verify the updated candidate's address


1. 2. 3. 4. 5. Select the statements from Task 2. On the toolbar, click Execute. Verify that the desired results are returned as 7194 Fourth St. Rockhampton. On the File menu, click Save All. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you have used XQuery with XML methods to view the selected contents of an XML schema and modified an XML object.

Exercise 4: Create XML Indexes


Task 1: Create a new query file
1. 2. 3. 4. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery6.sql As. The Save File As dialog box appears. In the File name field, type CreateXMLIndexes.sql, and then click Save.

20

Lab Answer Key: Using XML

Task 2: Create XML indexes


1. In the query window, type the following code to create the primary XML index on the Diagram column of the Production.Illustration table:
USE AdventureWorks2008 GO SET ARITHABORT ON CREATE PRIMARY XML INDEX PXML_Illustration_Diagram ON Production.Illustration (Diagram) WITH (FILLFACTOR = 60, PAD_INDEX = ON)

2.

In the query window, below the existing code, type the following code to create the secondary path XML index on the Diagram column of the Production.Illustration table:
CREATE XML INDEX XMLPATH_Illustration_Diagram ON Production.Illustration (Diagram) USING XML INDEX PXML_Illustration_Diagram FOR PATH WITH (FILLFACTOR = 70, PAD_INDEX = OFF) GO

3. 4. 5. 6. 7. 8. 9.

On the toolbar, click Execute to execute the query. Examine the Messages box and verify that the script completed without any errors. On the File menu, click Save All. In the navigation pane, expand Databases | AdventureWorks2008 | Tables | Production.Illustration | Indexes. Verify that the new XML indexes are listed and are correct. Close SQL Server Management Studio. Turn off 6232A-NY-SQL-01 and delete changes.
Results: After this exercise, you have created XML indexes.

Lab Answer Key: Implementing Views

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

Lab Answer Key: Implementing Views

Lab: Implementing Views


Exercise 1: Creating Views
Task 1: Create a SQL Server Scripts project
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Administrator using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008 | SQL Server Management Studio. The Connect to Server dialog box appears. Click Connect. On the File menu, point to New, and then click Project. The New Project dialog box appears. In the Templates box, make sure SQL Server Scripts is highlighted. In the Name field, type AW_Views. In the Location field, type E:\Mod06\Labfiles\Starter. Clear the Create directory for solution check box.

10. Click OK. 11. In the Solution Explorer pane, right-click Queries, and then click New Query. 12. If the Connect to Server dialog box appears, click Connect. 13. On the File menu, click Save SQLQuery1.sql As. 14. The Save File As dialog box appears. In the File name field, type CreateEmployeeView.sql, and then click Save.

Lab Answer Key: Implementing Views

Task 2: Create the HumanResources.vEmployeeDetails view


1. In the query window, type the following Transact-SQL code to create the HumanResources.vEmployeeDetails view:
USE AdventureWorks2008 GO CREATE VIEW HumanResources.vEmployeeDetails WITH SCHEMABINDING AS SELECT e.BusinessEntityID ,c.Title ,c.FirstName ,c.MiddleName ,c.LastName ,c.Suffix ,e.JobTitle ,c.EmailPromotion ,a.AddressLine1 ,a.AddressLine2 ,a.City ,sp.Name AS StateProvinceName ,a.PostalCode ,cr.Name AS CountryRegionName ,c.AdditionalContactInfo FROM HumanResources.Employee e INNER JOIN Person.Person c ON c.BusinessEntityID = e.BusinessEntityID INNER JOIN Person.BusinessEntityAddress ea ON e. BusinessEntityID = ea. BusinessEntityID INNER JOIN Person.Address a ON ea.AddressID = a.AddressID INNER JOIN Person.StateProvince sp ON sp.StateProvinceID = a.StateProvinceID INNER JOIN Person.CountryRegion cr ON cr.CountryRegionCode = sp.CountryRegionCode

2. 3. 4. 5. 6.

On the toolbar, click Execute. Examine Messages box and verify that the script completed without any errors. On the File menu, click Save All. In Object Explorer, expand Databases | AdventureWorks2008 | Views. Verify that the HumanResources.vEmployeeDetails view is listed.

Lab Answer Key: Implementing Views

7. 8.

In Object Explorer, expand Databases | AdventureWorks2008 | Views | HumanResources.vEmployeeDetails | Columns. Verify that the correct columns are listed in the view.

Task 3: Test the HumanResources.vEmployeeDetails view


1. 2. 3. 4. 5. In the Solution Explorer, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery2.sql As. The Save File As dialog box appears. In the File name field, type TestEmployeeView.sql, and then click Save. In the query window, type the following code:
Use AdventureWorks2008 SELECT * FROM HumanResources.vEmployeeDetails

6. 7. 8. 9.

On the toolbar, click Execute. Examine the Results and Messages boxes and verify that the script completed without any errors. Verify that correct data is returned from the view. On the File menu, click Save All.

10. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you should have created and tested of a new view for the database.

Lab Answer Key: Implementing Views

Exercise 2: Creating Indexed Views


Task 1: Create a new query file
1. 2. 3. 4. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery3.sql As. The Save File As dialog box appears. In the File name field, type CreateViewIndex.sql, and then click Save.

Task 2: Create the IX_vEmployeeDetails index


1. In the query window, type the following Transact-SQL code to create the IX_vEmployeeDetails index on the HumanResources.vEmployeeDetails view.
USE AdventureWorks2008 GO CREATE UNIQUE CLUSTERED INDEX IX_vEmployeeDetails ON HumanResources.vEmployeeDetails (BusinessEntityID)

2. 3. 4. 5.

On the toolbar, click Execute. Examine Messages box and verify that the script completed without any errors. On the File menu, click Save All. In Object Explorer, under Databases, ensure that AdventureWorks2008 | Views | HumanResources.vEmployeeDetails are expanded, and then expand Indexes. Verify that the IX_vEmployeeDetails index is listed. Keep SQL Server Management Studio open. You will use it in the next exercise.
Results: After this exercise, you should have created a new view index.

6. 7.

Lab Answer Key: Implementing Views

Exercise 3: Creating Partitioned Views


Task 1: Prepare the SQL Server instances
1. 2. 3. 4. Click Start, and then click Computer. In Microsoft Windows Explorer, navigate to the E:\Mod06\Labfiles\Starter folder. Double-click LabSetup.cmd to run the script that configures the servers for the partitioned view. When the script completes, close Windows Explorer.

Task 2: Create a new query file


1. 2. 3. 4. In the Solution Explorer pane, right-click Queries, and then click New Query. If the Connect to Server dialog box appears, click Connect. On the File menu, click Save SQLQuery4.sql As. The Save File As dialog box appears. In the File name field, type CreatePartitionedView.sql, and then click Save.

Task 3: Create the Person.vContact distributed partitioned view


1. In the query window, type the following code to create the distributed partitioned view named Person.vContact on the AW_Contacts database:
USE AW_Contacts GO CREATE VIEW Person.vContact AS SELECT * FROM [NY-SQL-01].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE2].AW_Contacts.Person.Contact UNION ALL SELECT * FROM [NY-SQL-01\SQLINSTANCE3].AW_Contacts.Person.Contact

2. 3. 4.

On the toolbar, click Execute. On the File menu, click Save All. In Object Explorer, right-click Databases, and then click Refresh.

Lab Answer Key: Implementing Views

5. 6. 7. 8. 9.

Under Databases, expand AW_Contacts, and then expand Views. Verify that the Person.vContact view is listed. In Object Explorer, under Databases, ensure that AW_Contacts | Views are expanded, expand Person.vContact, and then expand Columns. Verify that the correct columns are listed. In the Solution Explorer pane, right-click Queries, and then click New Query.

10. If the Connect to Server dialog box appears, click Connect. 11. On the File menu, click Save SQLQuery5.sql As. 12. The Save File As dialog box appears. In the File name field, type ViewPersonContact.sql, and then click Save. 13. In the query window, type the following code to select the contents of the Person.vContact view:
USE AW_Contacts GO SELECT * FROM Person.vContact

14. On the toolbar, click Execute. 15. Examine the Results and Messages boxes and verify that the script completed without any errors. 16. Verify that the result set of the Person.vContact view contains the data from the Person.Contact tables on all three SQL Server instances. 17. On the File menu, click Save All. 18. Close SQL Server Management Studio. 19. Turn off 6232A-NY-SQL-01 and delete changes.
Results: After this exercise, you should have configured and tested a new partitioned view for the SQL Server.

Lab Answer Key: Implementing Stored Procedures

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

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. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Student with the password of Pa$$w0rd. Click Start, right-click Computer and then click Explore. In Windows Explorer browse to E:\MOD07\Labfiles\Starter. Double-click the AWProgrammability.ssmssqlproj project file. The Microsoft SQL Server Management Studio window opens. If the Solution Explorer is not visible in the right pane, click View | Solution Explorer. In the Solution Explorer, double-click InitilizeData.sql. If the Connect to Sever dialog box appears, connect to server NY-SQL-01 using Windows Authentication. Click Connect. On the toolbar, click Execute, and then confirm that no errors occur.

10. In Solution Explorer, double-click the StoredProcedures.sql query file. 11. If the Connect to Sever dialog box appears, connect to server NY-SQL-01 using Windows Authentication. Click Connect. 12. Select the Use AdventureWorks2008 statement, and then on the toolbar, click Execute. 13. Select the text between the --Create GetDiscount comment and the following comment. 14. On the toolbar, click the Execute button to execute the selected text.

Lab Answer Key: Implementing Stored Procedures

15. To test the GetDiscount stored procedure: select the text between the Test GetDiscounts comment and the following comment. 16. On the toolbar, click the Execute button. 17. Verify the query runs with no errors.

Task 2: Create and test the GetDiscountsForCategory stored procedure


1. 2. 3. 4. 5. Select the text between the --Create GetDiscountsForCategory comment and the following comment. On the toolbar, click the Execute button to execute the selected text. To test the GetDiscountsForCategory stored procedure: select the text between the -- Test GetDiscountsForCategory comment and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors.

Task 3: Create and test the GetDiscountsForCategoryAndDate stored procedure


1. 2. 3. Select the text between the --Create GetDiscountsForCategoryAndDate comment and the following comment. On the toolbar, click the Execute button to execute the selected text To test the GetDiscountsForCategoryAndDate stored procedure: select the text between the -- Test GetDiscountsForCategoryAndDate comment and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors. Select the text between the comment -- Test GetDiscountsForCategoryAndDate with both parameters and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors.

4. 5. 6.

7. 8.

Lab Answer Key: Implementing Stored Procedures

Task 4: Create and test the AddDiscount stored procedure


1. 2. 3. 4. 5. 6. Select the text between the Create AddDiscount comment and the following comment. On the toolbar, click the Execute button to execute the selected text. To test the AddDiscount stored procedure: select the text between the -- Test AddDiscount comment and the following comment. On the toolbar, click the Execute button. Verify the query runs with no errors. To test executing the query with variables that generate an error, select all code between the comments -- Test AddDiscount with errors and the following comment, and then click Execute. Verify that an error log record is returned in the results pane.
Results: After this exercise, you should have created and tested 4 stored procedures.

7.

Exercise 2: Working with Execution Plans


Task 1: View the text-based execution plan
1. 2. 3. 4. In the Query window, select the code between the comment Test the textbased execution plan and the following comment. On the toolbar, click Execute. Observe in the results pane both the query and the text based execution plan are displayed instead of query results. Observe that the execution plan displays query parts in hierarchical order from most to least expensive operation.

Task 2: View the graphical execution plan


1. 2. 3. In the Query window, select the code between the comment Test the graphical execution plan and the following comment. Right-click the selection and then click Include Actual Execution Plan. On the toolbar, click Execute.

Lab Answer Key: Implementing Stored Procedures

4. 5. 6.

In the Results pane, observe that query results are returned. Observe the Execution Plan tab above the returned results. Click the Execution Plan tab. Observe that the execution plan shows that 0% of the executions work was involved in the SELECT statement, 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. 2. In the Query window select the code between the comment --Tune the database. Create an index on Name and the following comment. On the toolbar, click Execute.

Task 4: View the revised execution plan


1. 2. 3. 4. 5. In the Query window select the code below the comment Retest the graphical execution plan. In the toolbar, click Execute. In the Results pane observe that query results are returned. Observe the Execution Plan tab above the returned results. Click the Execution Plan tab. Observe that the execution plan shows that 0% of the executions work was involved in the SELECT statement, that 68% of the work was involved in the sort and 32% was involved in the clustered index scan. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab.
Results: After this exercise, you should have created and viewed both text-based and graphical execution.

6.

Lab Answer Key: Implementing Functions

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

Lab Answer Key: Implementing Functions

Lab: Implementing Functions


Exercise 1: Creating Functions
Task 1: Create and test the GetMaximumDiscountForCategory Userdefined function
1. 2. 3. 4. 5. 6. 7. 8. 9. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on as Administrator with the password of Pa$$w0rd. From the Start Menu, right-click Computer, and then click Explore. In Windows Explorer, browse to E:\MOD08\Labfiles\Starter. Double-click createnewuser.vbs. Click OK. Open Command Prompt. Browse to E:\MOD08\Labfiles\Starter. Type sqlcmd -E -i changeAW2008dbowner.sql and then press ENTER. Log off Administrator and then log on as Student with the password of Pa$$w0rd. From the Start Menu, right-click Computer, and then click Explore.

10. In Windows Explorer, browse to E:\MOD08\Labfiles\Starter. 11. Double-click the AWProgrammability solution file. The SQL Server Management Studio window opens. 12. If the Solution Explorer is not visible in the right pane, click View | Solution Explorer in the File menu. 13. In the Solution Explorer, expand AWProgramability | Queries. 14. Double-click InitilizeData.sql. 15. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. 16. The query appears. On the toolbar, click Execute, and then confirm that no errors occur. 17. In Solution Explorer, double-click the UserDefinedFunctions.sql query file.

Lab Answer Key: Implementing Functions

18. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. 19. Select the Use AdventureWorks2008 statement. On the toolbar, click Execute. 20. Locate the Create Sales.GetMaximumDiscountForCategory comment. Select the CREATE FUNCTION code shown in the following Transact-SQL example:
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

21. On the Toolbar, click Execute. 22. In the Results pane, review the query results, verifying that the statement executed successfully. 23. Locate the Test Sales.GetMaximumDiscountForCategory comment, and then test the function, as shown in the following Transact-SQL example:
SELECT Sales.GetMaximumDiscountForCategory('Reseller')

24. Select the query, and then on the toolbar, click Execute. In the Query results, verify that a discount value is returned. 25. On the File menu, click Save UserDefinedFunctions.sql.

Lab Answer Key: Implementing Functions

Task 2: Create and test the GetDiscountsForDate User-defined function


1. Locate the Create Sales.GetDiscountsForDate comment, and then create the user-defined function, as shown in the following Transact-SQL example:
CREATE FUNCTION Sales.GetDiscountsForDate (@DateToCheck datetime) RETURNS TABLE AS RETURN ( SELECT Description, DiscountPct, Type, Category, StartDate, EndDate, MinQty, MaxQty FROM Sales.SpecialOffer WHERE @DateToCheck BETWEEN StartDate AND EndDate )

2. 3. 4.

Select the CREATE FUNCTION statement. On the toolbar, click Execute. In the Results pane, review the query results, verifying that the statement executed successfully. Locate the Test Sales.GetDiscountsForDate comment, select the TransactSQL statement shown below in the following Transact-SQL example:
SELECT * FROM Sales.GetDiscountsForDate(GetDate()) ORDER BY DiscountPct DESC

5. 6.

On the toolbar, click Execute. In the query results, verify that some rows are displayed. On the File menu, click Save UserDefinedFunctions.sql.

Lab Answer Key: Implementing Functions

Task 3: Create and test the GetDiscountedProducts User-defined function


1. Locate the Create Sales.GetDiscountedProducts comment. Select the code to create the user-defined function as shown in the following Transact-SQL example:
CREATE FUNCTION Sales.GetDiscountedProducts (@IncludeHistory bit) RETURNS @tbl_products TABLE (ProductID int, Name nvarchar(50), ListPrice money, DiscountDescription nvarchar(255), DiscountPercentage smallmoney, DiscountAmount money, DiscountedPrice money) AS BEGIN IF (@IncludeHistory = 1) INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice * SO.DiscountPct 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) ORDER BY ProductID ELSE INSERT @tbl_products SELECT P.ProductID, P.Name, P.ListPrice, SO.Description, SO.DiscountPct, P.ListPrice * SO.DiscountPct, P.ListPrice - P.ListPrice *

Lab Answer Key: Implementing Functions

(continued)
SO.DiscountPct 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

2. 3. 4.

On the toolbar, click Execute. In the Results pane, review the query results. Verify that the statement executed successfully. Locate the Test Sales.GetDiscountedProducts comment; select the code as shown in the following Transact-SQL example:
SELECT * FROM Sales.GetDiscountedProducts(0) SELECT * FROM Sales.GetDiscountedProducts(1)

5. 6.

On the toolbar, click Execute. In the query results, view the number of rows returned by each query. On the File menu, click Save UserDefinedFunctions.sql.
Results: After this exercise, you should have created and tested 3 user-defined functions.

Lab Answer Key: Implementing Functions

Exercise 2: Controlling Execution Context


Task 1: Create the GetCurrencyRate User-defined function
1. 2. 3. 4. In Solution Explorer, double-click the ExecutionContext.sql query file. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. Select the USE AdventureWorks2008 statement. On the toolbar, click Execute. Locate the Create Sales.GetCurrencyRate comment, and then create the userdefined function, as shown in the following Transact-SQL example:
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

5. 6. 7.

Select the CREATE FUNCTION statement. On the toolbar, click Execute. In the Results pane, review the query results. Verify that the statement executed successfully. Locate the Test Sales.GetCurrencyRate comment, and then test the function, as shown in the following Transact-SQL example:
SELECT Sales.GetCurrencyRate('GBP')

Lab Answer Key: Implementing Functions

8.

Select the SELECT statement. On the toolbar, click Execute.

Note: At this stage you have not established a trust relationship between the databases, 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.

9.

On the File menu, click Save ExecutionContext.sql.

Task 2: Establish a database trust relationship


1. 2. 3. 4. In Solution Explorer, double-click the TrustRelationship.sql query file. If the Connect to Sever box appears, connect to server NY-SQL-01 using Windows Authentication. Select the USE AdventureWorksDW2008 statement. Click Execute. Locate the Create the user for the NY-SQL-01\Adam login comment, and then create a user called Adam in the AdventureWorksDW2008 database for the NY-SQL-01\Adam login, as shown in the following Transact-SQL example:
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. 7. 8.

Select the IF and CREATE statements. On the toolbar, click Execute. Verify that the statements executed successfully. Locate the Grant AUTHENTICATE permission on the database comment. Implement the Transact-SQL code required to grant the mapped user AUTHENTICATE permission in the AdventureWorksDW2008 database, as shown in the following Transact-SQL example:
GRANT AUTHENTICATE TO Adam GO

Lab Answer Key: Implementing Functions

9.

Select the GRANT statement. On the toolbar, click Execute.

10. Verify that the statement executed successfully. 11. Locate the Grant SELECT permissions to Adam comment, and then implement the Transact-SQL code required to grant the authenticator the permissions required by the user-defined function in the calling database, as shown in the following Transact-SQL example.
GRANT SELECT TO Adam GO

12. Select the GRANT statement. On the toolbar, click Execute. 13. Verify that the statement executed successfully. 14. Locate the Set the TRUSTWORTHY database option on the AdventureWorks2008 database comment, and then implement the TransactSQL code required to alter the calling database and set the TRUSTWORTHY option to ON, as shown in the following Transact-SQL example:
ALTER DATABASE AdventureWorks2008 SET TRUSTWORTHY ON GO

15. Select the ALTER statement. On the toolbar, click Execute. 16. Verify that the statement executed successfully. 17. On the File menu, click Save TrustRelationship.sql.

10

Lab Answer Key: Implementing Functions

Task 3: Create and test the GetCurrencyDiscountedProducts Userdefined Function


1. 2. 3. In Solution Explorer, double-click the ExecutionContext.sql query file. Select the USE AdventureWorks2008 statement. On the toolbar, click Execute. Locate the Sales.GetCurrencyDiscountedProducts comment, as shown 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

Lab Answer Key: Implementing Functions

11

4. 5. 6.

Select the CREATE FUNCTION statement. On the toolbar, click Execute. Verify that the statement executed successfully. Locate the Test Sales.GetCurrencyDiscountedProducts comment, and then test the function, as shown in the following Transact-SQL example:
SELECT * FROM Sales.GetCurrencyDiscountedProducts('GBP')

7. 8. 9.

Select the SELECT statement. On the toolbar, click Execute. Review the query results and verify that the statement executed successfully. On the File menu, click Save All, and then close SQL Server Management Studio.

10. Turn off 6232A-NY-SQL-01 virtual machine and discard any changes.
Results: After this exercise, you should have created two user-defined functions and created a trust relationship between the AdventureWorks2008 and AdventureWorksDW2008.

Lab Answer Key: Implementing Managed Code in a Database

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

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. 3. 4. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Administrator using the password of Pa$$w0rd. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect.
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

Lab Answer Key: Implementing Managed Code in a Database

Task 2: Import the AWorksUtilities assembly


1. 2. 3. 4. 5. 6. 7. On the File menu, point to Open, and then click Project/Solution. In the Open Project dialog box, browse to the E:\MOD09\Labfiles\Starter folder click the AWorks_CLR.ssmssln file, and then click Open. If Solution Explorer is not visible, on the View menu, click Solution Explorer. In Solution Explorer, expand the Queries node, and then double-click the Initialize.sql query file. On the toolbar, click Execute, and then confirm that no errors occur. In Solution Explorer, double-click the ImportAssembly.sql query file. Below the Enable CLR integration comment, add the following code:
sp_configure 'clr enabled', 1 GO RECONFIGURE GO

8. 9.

On the toolbar, click Execute, and then verify that the statements executed successfully. Below the Create assembly comment, add the following code:
USE AdventureWorks2008 CREATE ASSEMBLY AWorksUtilities FROM 'E:\MOD09\Labfiles\Starter\AWorksUtilities.dll'

10. Below the Create assembly comment, select all the code, and then on the toolbar, click Execute. 11. In the query results, verify that the statements executed successfully. 12. On the File menu, click Save ImportAssembly.sql. 13. Keep the SQL Server Management Studio solution open. You will use it in the next exercise.
Results: After this exercise, you should have the managed database objects in the AWorksUtilities assembly available for use within the AdventureWorks2008 database.

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. 2. In Solution Explorer, double-click the SaveXML.sql query file. Locate the Create managed stored procedure comment, and then add the following code:
USE AdventureWorks2008 GO CREATE PROCEDURE dbo.SaveXML ( @XmlData xml, @FileName nvarchar(100) ) AS EXTERNAL NAME AWorksUtilities.StoredProcedures.SaveXML GO

3. 4. 5. 6. 7.

Below the Create managed stored procedure comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test managed stored procedure comment, select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. Confirm that an error message is displayed. The assembly does not have the required permissions to write to the file system. Below the Change security permissions to allow file access comment, add the following code:
ALTER ASSEMBLY AWorksUtilities WITH PERMISSION_SET = EXTERNAL_ACCESS GO

8. 9.

Select the ALTER ASSEMBLY statement, and then on the toolbar, click Execute. In the query results, verify that the statements executed successfully.

10. Below the Retest managed stored procedure comment, select the DECLARE, SET, and EXEC statements, and then on the toolbar, click Execute. 11. Confirm that no errors occur this time.

Lab Answer Key: Implementing Managed Code in a Database

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

Lab Answer Key: Implementing Managed Code in a Database

Task 2: Create the GetLongDate managed user-defined function referencing the external assembly
1. 2. In Solution Explorer, double-click the GetLongDate.sql query file. Below the Create managed user-defined function comment, add the following code:
USE AdventureWorks2008 GO CREATE FUNCTION dbo.GetLongDate ( @DateVal datetime ) RETURNS nvarchar(50) AS EXTERNAL NAME AWorksUtilities.UserDefinedFunctions.GetLongDate GO

3. 4. 5. 6. 7. 8.

Below the Create managed user-defined function comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test managed user-defined function comment, select the SELECT statement, and then on the toolbar, click Execute. Verify that a list of orders is displayed that includes the day of the week in the OrderDate column. Confirm that the records are displayed with a long OrderDate value. On the File menu, click Save GetLongDate.sql.

Lab Answer Key: Implementing Managed Code in a Database

Task 3: Create the EmailChange managed trigger on the Person.EmailAddress table referencing the external assembly
1. 2. In Solution Explorer, double-click the EmailChange.sql query file. Below the Create trigger comment, add the following code:
USE AdventureWorks2008 GO CREATE TRIGGER EmailChange ON Person.EmailAddress FOR UPDATE AS EXTERNAL NAME AWorksUtilities.Triggers.EmailChange GO

3. 4. 5. 6. 7. 8.

Below the Create trigger comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test trigger comment, select the first UPDATE statement, and then on the toolbar, click Execute. Confirm that a message is displayed, noting the new e-mail address in the Messages pane. Below the Test trigger comment, select the second UPDATE statement, and then on the toolbar, click Execute. Confirm that there is no message because the statement did not update the email address. 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. On the File menu, click Save EmailChange.sql.

9.

Lab Answer Key: Implementing Managed Code in a Database

Task 4: Create the Concatenate managed aggregate function referencing the external assembly
1. 2. In Solution Explorer, double-click the Concatenate.sql query file. Below the Create aggregate function comment, add the following code:
USE AdventureWorks2008 GO CREATE AGGREGATE Concatenate(@input nvarchar(4000)) RETURNS nvarchar(4000) EXTERNAL NAME AWorksUtilities.Concatenate GO

3. 4. 5. 6. 7.

Below the Create aggregate function comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test aggregate function comment, select the SELECT statement, and then on the toolbar, click Execute. Confirm that orders are displayed as a concatenated string for each account in the Messages pane. On the File menu, click Save Concatenate.sql.

Lab Answer Key: Implementing Managed Code in a Database

Task 5: Create the IPAddress managed user-defined type referencing the external assembly
1. 2. In Solution Explorer, double-click the IPAddress.sql query file. Below the Create managed user-defined type comment, add the following code:
USE AdventureWorks2008 GO CREATE TYPE IPAddress EXTERNAL NAME AWorksUtilities.IPAddress GO

3. 4. 5. 6. 7. 8. 9.

Below the Create managed user-defined type comment, select the code, and then on the toolbar, click Execute. Verify that the statements executed successfully. Below the Test managed user-defined type comment, select the statements, and then on the toolbar, click Execute. Confirm that three result sets are displayed that show the IPAddress value in various forms. On the File menu, click Save IPAddress.sql. Close the SQL Server Management Studio solution. Shutdown the virtual machine and do not save changes when prompted to reset for the next lab.
Results: After this exercise, you should have successfully imported assembly code and created managed database objects.

Lab Answer Key: Managing Transactions and Locks

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

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. 2. In the Lab Launcher, next to 6231A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd.

Task 2: Create and commit a transaction


1. 2. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect:
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

3. 4.

On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Tran1.sql, and then click Open.

Lab Answer Key: Managing Transactions and Locks

5.

In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

6.

Locate the comment START TRANSACTION HERE, and then add a statement to start a transaction. Your code should resemble the following:
BEGIN TRANSACTION

7.

Click Execute to execute the script, and then review the results. At this point, the transaction is still active and locks are still held. The changes made have not been committed to the database. Locate the comment END TRANSACTION HERE, and then add a statement to commit the changes to the database. Your code should resemble the following:
COMMIT TRANSACTION

8.

9.

Select the end transaction statement, and then click Execute. The changes are now committed to the database.

10. Select the last two statements in the script, and then click Execute. 11. Verify that the transaction count is now set to zero and the changes have been committed to the database. 12. On the File menu, click Save Tran1.sql. 13. On the File menu, click Close.

Lab Answer Key: Managing Transactions and Locks

Task 3: Create and rollback a transaction


1. 2. 3. On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Tran2.sql, and then click Open. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

4.

Notice that the statements update a different record in the Person.Person table. Again, the SELECT statements and the @@trancount global variable show the progress of the transaction. Locate the comment END TRANSACTION HERE, and then add a statement to roll back the changes to the database. Your code should resemble the following:
ROLLBACK TRANSACTION

5.

6.

Click Execute to execute the script, and then review the results. Notice that the transaction is complete because the transaction count is zero and the changes have been cancelled. On the File menu, click Save Tran2.sql. Close SQL Server Management Studio.
Results: After this exercise, you should have committed and rolled back transactions.

7. 8.

Lab Answer Key: Managing Transactions and Locks

Exercise 2: Managing Locks


Task 1: View locking information
1. 2. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect:
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

3. 4. 5. 6.

In SQL Server Management Studio, in the console tree, right-click NY-SQL-01, and then click Activity Monitor. Review the information that is displayed in Processes, ResourceWaits, and Data File I/O, and Recent Expensive Queries. On the File menu, point to New, and then click Query with Current Connection. Type the following statement into the query window:
SELECT resource_type, request_mode, request_type, request_status, request_session_id FROM sys.dm_tran_locks

7. 8. 9.

Click Execute to execute the statement. Review the information that shows the current lock in the master database. On the File menu, point to Open, and then click File.

10. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Lock1.sql, and then click Open.

Lab Answer Key: Managing Transactions and Locks

11. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

12. Notice that a transaction starts with the BEGIN TRANSACTION statement, but there is no corresponding COMMIT TRANSACTION or ROLLBACK TRANSACTION statement to complete the transaction. 13. Click Execute to execute the script and note the SPID of the connection. 14. Switch back to the original query window and then click Execute to execute the query and retrieve data from the sys.dm_tran_locks view. Notice that now the SPID of the second connection holds locks on various objects. 15. In SQL Server Management Studio, in the console tree, right-click NY-SQL01, and then click Activity Monitor. 16. Review the information that is now displayed in Overview, Processes, and Resource Waits. 17. Switch to the Lock1.sql query window, type the following code at the end of the script, and then execute the statement:
ROLLBACK TRANSACTION

18. Switch back to the original query window, and then click Execute to execute the query and retrieve data from the sys.dm_tran_locks view. 19. Notice that the object locks acquired during the transaction have now been released. 20. Close SQL Server Management Studio without saving the changes to the files.

Lab Answer Key: Managing Transactions and Locks

Task 2: Set locking options


1. 2. Click Start, point to All Programs, point to Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, specify the values in the following table, and then click Connect:
Property Server type Server name Authentication Value Database Engine NY-SQL-01 Windows Authentication

3. 4. 5.

On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Lock1.sql, and then click Open. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

6. 7. 8. 9.

Review the contents of the file, and then execute the query. On the File menu, point to Open, and then click File. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click Lock2.sql, and then click Open. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

Lab Answer Key: Managing Transactions and Locks

10. Review the contents of the file and notice that the transaction isolation level is set to SERIALIZABLE, which prevents other users from accessing rows that match the criteria in a WHERE clause.

Note: In the next step, you will execute the query. Continue with the exercise and do not wait for the execution to complete.

11. Click Execute to execute the query. 12. On the File menu, point to Open, and then click File. 13. In the Open File dialog box, browse to the E:\Mod10\Labfiles\Starter folder, click LockList.sql, and then click Open. 14. In the Connect to Database Engine dialog box, specify the values in the following table, and then click Connect:
Property Server name Authentication Value NY-SQL-01 Windows Authentication

15. Click Execute to execute the query and notice that there is an entry of WAIT in the request_status column, which indicates that the second query is waiting for a lock to be granted before proceeding. 16. Switch to the Lock2.sql query window, and then click Cancel Executing Query. 17. Switch to the LockList.sql query window, and then click Execute to execute the query. 18. Verify that the waiting transaction has been cancelled.

Lab Answer Key: Managing Transactions and Locks

Task 3: Set the lock timeout


1. Switch to the Lock2.sql query window, and then edit the file by adding the following statement immediately before the BEGIN TRANSACTION statement:
SET lock_timeout 5000

2. 3. 4.

Click Execute to execute the query and wait five seconds. Notice that the query no longer waits indefinitely for the lock to be granted. Close SQL Server Management Studio without saving the changes to the files. Turn off the virtual machine and delete changes.
Results: After this exercise, you should have set locking options and timeouts.

Lab Answer Key: Using Service Broker

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

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. 3. 4. In the Lab Launcher, next to 6232A-NY-SQL-01, click Launch. Log on to NY-SQL-01 as Student using the password Pa$$w0rd. Click Start | All Programs | Microsoft SQL Server 2008, and then click SQL Server Management Studio. In the Connect to Server dialog box, verify that Server type is set to Database Engine and Server name is set to NY-SQL-01, and then click Connect.

Task 2: Create the AW_ServiceBroker SQL Server Scripts project


1. 2. 3. 4. On the File menu, point to New, and then click Project. In the New Project dialog box, in the Name field, type AW_ServiceBroker. In the Location field, type E:\MOD11\Labfiles\Starter. Clear Create directory for solution and then click OK.

Task 3: Configure the AdventureWorks database for Service Broker


1. 2. 3. 4. 5. On the Project menu, click New Query to add a new query file to the project. If the Connect to Database Engine dialog box appears, click Connect. If Solution Explorer is not visible, on the View menu, click Solution Explorer. In Solution Explorer, in the Queries folder, right-click SQLQuery1.sql, click Rename, type PrepareDatabase.sql, and then press ENTER. Notice how the name of the query in the design pane has automatically changed to PrepareDatabase.sql.

Lab Answer Key: Using Service Broker

6.

Add the following Transact-SQL code to the PrepareDatabase.sql query:


USE master GO -- Enable Service Broker in the AdventureWorks2008 database ALTER DATABASE AdventureWorks2008 SET SINGLE_USER WITH ROLLBACK IMMEDIATE GO ALTER DATABASE AdventureWorks2008 SET ENABLE_BROKER GO -- Configure the AdventureWorks2008 database USE AdventureWorks2008 GO IF NOT EXISTS (SELECT * FROM sys.symmetric_keys WHERE name = '##MS_DatabaseMasterKey##') CREATE MASTER KEY ENCRYPTION BY PASSWORD = '23987hxJ#KL95234nl0zBe' GO CREATE SCHEMA EMailSvc GO CREATE SCHEMA CustomerSvc GO -- Create a table to log details of the customer e-mails sent CREATE TABLE EMailSvc.EmailLog ( Date datetime NOT NULL, [Event] nvarchar(50) NOT NULL, CustomerData xml ) GO ALTER DATABASE AdventureWorks2008 SET MULTI_USER GO

7. 8.

On the toolbar, click Execute to execute the query. On the File menu, click Save All.

Lab Answer Key: Using Service Broker

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

Lab Answer Key: Using Service Broker

4. 5. 6. 7. 8.

On the toolbar, click Execute to execute the query. On the File menu, click Save All. If Object Explorer is not visible, on the View menu, click Object Explorer. In Object Explorer, expand Databases, expand AdventureWorks2008, and then expand Service Broker. In the Service Broker folder, expand the Message Types, Contracts, Queues, and Services folders, and then verify that the necessary Service Broker objects are listed. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have launched SQL Server Management Studio and created the AW_ServiceBroker SQL Server Scripts project. In addition, you should have configured the AdventureWorks database for Service Broker and then created the Service Broker objects required for the customer e-mail solution.

9.

Exercise 2: Implementing the Initiating Service


Task 1: Add the CreateEmailNewCustomerSP.sql query file to the AW_ServiceBroker project
1. 2. On the Project menu, click Add Existing Item. In the Add Existing Item AW_ServiceBroker dialog box, browse to the E:\MOD11\Labfiles\Starter folder, click the CreateEmailNewCustomerSP.sql query file, and then click Add.

Lab Answer Key: Using Service Broker

Task 2: Implement the CustomerService service


1. Examine the Transact-SQL code in the CreateEmailNewCustomerSP.sql query file. 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. On the toolbar, click Execute to execute the query. On the File menu, click Save All. In Object Explorer, under AdventureWorks2008, expand Programmability, and then expand Stored Procedures. Verify that the CustomerSvc.uspEmailNewCustomer stored procedure is listed. Keep Microsoft SQL Server Management Studio open for the next exercise.
Results: After this exercise, you should have created the CustomerSvc.uspEmailNewCustomer stored procedure used by the service.

2. 3. 4. 5. 6.

Exercise 3: Implementing the Target Service


Task 1: Add the CreateSendEmailSP.sql query file to the AW_ServiceBroker project
1. 2. On the Project menu, click Add Existing Item. In the Add Existing Item AW_ServiceBroker dialog box, browse to the E:\MOD11\Labfiles\Starter folder, click the CreateSendEmailSP.sql query file, and then click Add.

Lab Answer Key: Using Service Broker

Task 2: Implement the EmailService service


1. Examine the Transact-SQL code in the CreateSendEmailSP.sql query file. 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. On the toolbar, click Execute to execute the query. On the File menu, click Save All. In Object Explorer, right-click Stored Procedures, and then click Refresh. Verify that the EMailSvc.uspSendCustomerEmail stored procedure is listed.

2. 3. 4. 5.

Task 3: Configure the target service for automatic activation


1. 2. 3. On the Project menu, click New Query. In Solution Explorer, right-click SQLQuery1.sql, click Rename, type AlterServiceBrokerQueue.sql, and then press ENTER. In the AlterServiceBrokerQueue.sql query window, type the following Transact-SQL statement to make the EMailSvc.NewCustomerEmailQueue queue activate the EMailSvc.uspSendCustomerEmail stored procedure:
USE AdventureWorks2008 GO ALTER QUEUE EMailSvc.NewCustomerEmailQueue WITH STATUS = ON, ACTIVATION ( STATUS = ON, PROCEDURE_NAME = AdventureWorks2008.EMailSvc.uspSendCustomerEmail, MAX_QUEUE_READERS = 5, EXECUTE AS OWNER)

4. 5.

On the toolbar, click Execute to execute the query. On the File menu, click Save All.

Lab Answer Key: Using Service Broker

Task 4: Test the EmailService service


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

3.

4. 5.

6. 7.

Вам также может понравиться