Академический Документы
Профессиональный Документы
Культура Документы
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
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
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 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 Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
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
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.
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.
Results: After this exercise, you should have created a table named ReturnedGoods, created a table named Refunds, and followed all provided specifications.
Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
Module 3
Lab Instructions: Creating and Tuning Indexes
Contents:
Exercise 1: Creating Indexes Exercise 2: Optimizing Indexes 2 4
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.
2.
Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
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
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.
2 3.
3. 4.
Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
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
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.
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.
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
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)
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.
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
Execute the code, and then verify that the HumanResources.JobCandidateHistory table is listed. Verify that the necessary columns have been successfully created.
10
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.
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.
11
Execute the code and verify that the script completed without any errors. Examine the XML record to confirm that it is complete and accurate.
12
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.
Execute the code and verify that the desired results are returned.
Execute the statements, and then verify that the desired results are returned.
14
Execute the statements, and then verify that the desired results are returned.
15
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
16
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.
Module 6
Lab Instructions: Implementing Views
Contents:
Exercise 1: Creating Views Exercise 2: Creating Indexed Views Exercise 3: Creating Partitioned Views 2 6 7
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.
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.
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.
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.
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.
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.
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:
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 Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
Module 7
Lab Instructions: Implementing Stored Procedures
Contents:
Exercise 1: Creating Stored Procedures Exercise 2: Working with Execution Plans 2 6
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.
2.
2.
3.
2.
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 Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
Module 8
Lab Instructions: Implementing Functions
Contents:
Exercise 1: Creating Functions Exercise 2: Controlling Execution Context 2 8
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.
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
14. Execute the statement below the comment Test Sales.GetMaximumDiscountForCategory as shown in the example below:
SELECT Sales.GetMaximumDiscountForCategory('Reseller')
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:
5.
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
(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.
5.
Save UserDefinedFunctions.sql.
Results: After this exercise, you should have created and tested 3 user-defined functions.
5.
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.
10
4.
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:
7. 8.
Locate the Grant SELECT permission to Adam comment. Execute the GRANT statement as show in the example below:
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.
11
4.
-- 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
7.
Test the function by execution the SELECT statement as shown in the following example:
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.
Module 9
Lab Instructions: Implementing Managed Code in a Database
Contents:
Exercise 1: Importing an Assembly Exercise 2: Creating Managed Database Objects 2 4
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.
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.
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.
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 Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
Module 10
Lab Instructions: Managing Transactions and Locks
Contents:
Exercise 1: Using Transactions Exercise 2: Managing Locks 2 4
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 Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
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
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
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
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.
3. 4.
Configure the AdventureWorks database for Service Broker. Create the Service Broker objects required for the customer e-mail solution.
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.
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.
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.
3.
Lab Shutdown
After you complete the lab, you must shut down the 6232A-NY-SQL-01 virtual machine and discard any changes.
Module 1
Lab Answer Key: Creating Databases and Database Files
Contents:
Exercise 1: Creating a Database Exercise 2: Creating a Schema Exercise 3: Creating a Database Snapshot 2 4 6
10. 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.
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.
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.
3. 4.
On the toolbar, click Execute. Close the query editor without saving the query.
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.
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.
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.
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
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.
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.
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
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.
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.
3.
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.
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.
Module 3
Lab Answer Key: Creating and Tuning Indexes
Contents:
Exercise 1: Creating Indexes Exercise 2: Optimizing Indexes 2 4
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.
10. In the details pane, notice that Total fragmentation has changed to 50.00%. 11. Click Cancel.
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 Answer Key: Implementing Data Integrity by Using Constraints and Triggers
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
4. 5.
Lab Answer Key: Implementing Data Integrity by Using Constraints and Triggers
3.
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.
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
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
5.
6.
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
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.
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.
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.
Task 2: Use the OPENXML function to insert the XML data into the tables
1. 2. In the Solution Explorer pane, double-click the OPENXML.sql query to open it. Examine the query and note that it provides a sample XML document that contains a sales order from a customer for two items. The remainder of the file is incomplete. Locate the comment Call stored procedure to create the memory tree, and then add a call to the sp_xml_preparedocument stored procedure, as shown in the following example:
EXEC sp_xml_preparedocument @docHandle OUTPUT, @doc
3.
4.
Locate the comment Add OPENXML function for SalesOrderHeader table INSERT, and then add an OPENXML function to retrieve the relevant attributes from the SalesOrder node, as shown in the following example:
OPENXML(@docHandle, '/SalesOrder', 1) WITH ( CustomerID int, OrderDate datetime, DueDate datetime, AccountNumber nvarchar(15), SalesPersonID int, BillToAddressID int, ShipToAddressID int, ShipMethodID int, SubTotal money, TaxAmt money)
5.
Locate the comment Add OPENXML function for SalesOrderDetail table INSERT, and then add an OPENXML function to retrieve the relevant subelements from the Item node, as shown in the following example:
OPENXML(@docHandle, '/SalesOrder/Item', 2) WITH ( OrderQty int, ProductID int, UnitPrice money)
6.
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.
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.
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
(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>
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
(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" />
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.
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
10. Notice that the Resume column is now associated with the HumanResources.HistoricResumeSchemaCollection.
15
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
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.
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.
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.
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
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.
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.
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.
20
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.
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
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.
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.
7. 8.
In Object Explorer, expand Databases | AdventureWorks2008 | Views | HumanResources.vEmployeeDetails | Columns. Verify that the correct columns are listed in the view.
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.
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.
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.
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.
Module 7
Lab Answer Key: Implementing Stored Procedures
Contents:
Exercise 1: Creating Stored Procedures Exercise 2: Working with Execution Plans 2 4
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.
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.
4. 5. 6.
7. 8.
7.
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.
6.
Module 8
Lab Answer Key: Implementing Functions
Contents:
Exercise 1: Creating Functions Exercise 2: Controlling Execution Context 2 7
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.
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.
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.
(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.
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')
8.
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.
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
9.
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
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.
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
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.
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.
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.
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.
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.
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.
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.
Module 10
Lab Answer Key: Managing Transactions and Locks
Contents:
Exercise 1: Using Transactions Exercise 2: Managing Locks 2 5
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.
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.
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.
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.
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.
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
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.
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.
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
6.
7. 8.
On the toolbar, click Execute to execute the query. On the File menu, click Save All.
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])
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.
2. 3. 4. 5. 6.
2. 3. 4. 5.
4. 5.
On the toolbar, click Execute to execute the query. On the File menu, click Save All.
3.
4. 5.
6. 7.