6232B ENU TrainerHandbook Vol2

Embed Size (px)

Citation preview

  • 20-20 Implementing a Microsoft SQL Server 2008 R2 Database

    Demonstration 2A: Implementing Full-Text Indexes

    Key Points

    In this demonstration you will see:

    How to create a full-text catalog

    How to create a full-text index

    How to check when a full-text index is fully populated

    Demonstration Steps

    1. If Demonstration 1A was not performed:

    Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.

    In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ.ssmssln and click Open.

    Open and execute the 00 Setup.sql script file from within Solution Explorer.

    2. Open the 21 Demonstration 2A.sql script file. 3. Follow the instructions contained within the comments of the script file.

  • Working with Full-Text Indexes and Queries 20-21

    Lesson 3 Working with Full-Text Queries

    The real power of using full-text indexes comes after the index has been built and populated and you begin to execute queries that make use of the index. There are two basic ways to execute queries using full-text indexes. Full-text predicates can be added to WHERE clauses. Alternately, tables of full-text results can be returned and queried or joined to other tables. It is also important to be able to exercise control over which words are included in the index and to use the thesaurus to provide synonyms or replacements for common search terms.

    Objectives

    After completing this lesson, you will be able to:

    Write queries using the CONTAINS predicate Write queries using the FREETEXT predicate Return CONTAINS and FREETEXT results as tables along with ranking of relevance Create stopwords and stoplists Add details of synonyms and replacements to a full-text thesaurus Manage and debug full-text indexes

  • 20-22 Implementing a Microsoft SQL Server 2008 R2 Database

    CONTAINS Queries

    Key Points

    Queries using the CONTAINS predicate search for words or combinations of words. They can also perform proximity searches and advanced searches using inflectional forms of words or synonyms and replacements from a thesaurus.

    CONTAINS

    The CONTAINS predicate is used to search for words. The most basic form of usage is shown in the first example on the slide. The query returns the MessageID and Description columns from the dbo.Messages table for each row where the Description column contains the word 'filing'.

    Boolean Logic

    Boolean logic can also be applied to search for combinations of words. In the second example shown in the slide, the query is changed so that only rows where the Description column contains the word 'file' but does not also contain the word 'boundary' are returned.

    The permitted Boolean operators are:

    AND AND NOT OR

    Proximity

    The CONTAINS predicate can also search for combinations of words using the NEAR operator. This is shown in the following WHERE clause:

    WHERE CONTAINS(Description, 'drive NEAR car')

    This predicate will filter rows where the Description column contains the word "drive" somewhere "near" the word "car". It is important to realize however, that NEAR is a relative term. Results are often more or

  • Working with Full-Text Indexes and Queries 20-23

    less relevant depending upon how near the search words are in the column. Later in this lesson, you will see how ranking the results of a proximity query usually provide more useful outcomes.

    Inflectional

    Earlier in the module, you learned how end users think of words like drive, drove, and driving as being different versions of the same word. In a CONTAINS query, you can include a search for these by using the FORMSOF function. This is shown in the following WHERE clause:

    WHERE CONTAINS(Description, 'FORMSOF(INFLECTIONAL, drive)')

    This predicate will filter rows where the Description column contains a word that is an inflectional form of the word "drive", such as "driving" or "drove".

    Thesaurus

    It is also useful to be able to search for words that are treated as having the same meaning within the organization. This is shown in the following WHERE clause:

    WHERE CONTAINS(Description, 'FORMSOF(THESAURUS,client)')

    This predicate will filter rows where the Description column contains words that have been configured as synonyms for the word "client". Later in the lesson, you will see how to configure a thesaurus to make these queries possible.

    Specified Relevance

    The CONTAINS predicate can also search for terms based upon the weighting that you assign to each term. This is shown in the following WHERE clause:

    WHERE CONTAINS(Description, 'ISABOUT (certificate weight (.8), symmetric weight (.4), key weight (.2) )')

    In this WHERE clause, the developer is telling SQL Server how important each search term is by assigning a weight to each term. In this example, the word 'certificate' is ranked as 0.8, the word 'symmetric' is ranked as 0.4 and the word 'key' is ranked as 0.2. The more important a search term is, the heigher the weight that should be assigned to it. Weights are values between 0 and 1.0.

    The ISABOUT function is another example where it is important to rank the relevance of the results returned. The ISABOUT function will be discussed later in the lesson.

  • 20-24 Implementing a Microsoft SQL Server 2008 R2 Database

    FREETEXT Queries

    Key Points

    FREETEXT queries are the most powerful form of full-text query. They depend upon SQL Server understanding the meaning of the term or phrase being searched for.

    FREETEXT

    The FREETEXT predicate allows for the creation of the most powerful forms of full-text query. Users can enter the details of the meaning of what they are looking for and SQL Server finds matches that are relevant.

    In the example shown in the slide, the MessageID and Description columns from the dbo.Messages table are being returned for any rows where the Description column contains a value that is relevant to the phrase 'statement was terminated'.

    Weighting

    SQL Server determines the relevance of the column data by internally assigning a weight to each of the search terms and then matching using the weights. This is very similar to the way the ISABOUT option works in the CONTAINS predicate but with FREETEXT, SQL Server automatically assigns the search term weightings based on an internal algorithm. This provides a result that makes it appear that SQL Server has "understood" the meaning of the search phrase.

  • Working with Full-Text Indexes and Queries 20-25

    Table Functions and Ranking Results

    Key Points

    Many of the CONTAINS and FREETEXT predicate options will return a large number of returned rows. Some will be more relevant than others. SQL Server can also provide a ranking on the relevance of the results when table-valued functions are used instead of WHERE clause predicates.

    CONTAINSTABLE

    CONTAINSTABLE is a table-valued function that returns the same rows that would have been filtered by a CONTAINS predicate but additionally provides a measure of relevance of each returned result via a RANK column that is returned in the table. It also provides a KEY column that determines the unique identity of the returned row so that it can be joined to the underlying table if necessary.

    FREETEXTTABLE

    FREETEXTTABLE is the table-valued function equivalent of the FREETEXT predicate. It also returns the same rows that would have been filtered by a FREETEXT predicate along with RANK and KEY columns.

    In the example shown in the slide, the MessageID and Description columns are being returned from the dbo.Messages table for rows where the Description column is relevant to the search phrase 'statement was terminated'. Note, however, that the rows that are filtered have been returned as a table which has then been joined back to the source dbo.Messages table.

    The table returned by the FREETEXTTABLE function includes a column named KEY that is then used to locate the row in the original table. In this example, it would be used to find entries in the dbo.Messages table based upon the value in the MessageID column.

    RANK

    Besides returning the relevant rows, CONTAINSTABLE and FREETEXTTABLE also return a measure of relevance of each returned row called RANK.

  • 20-26 Implementing a Microsoft SQL Server 2008 R2 Database

    In the example shown in the slide, the query returns an output where the resultant rows are arranged by the RANK descending. This will return the most relevant rows first. You will see an example of this in the next demonstration.

    Note that the value returned by the RANK column is only meaningful within the table of results that are returned during that particular execution of the query. The value cannot be used to compare with other CONTAINSTABLE or FREETEXTTABLE function return values.

    Question: Would a search engine be more likely to use the table forms of these or the predicate forms?

  • Working with Full-Text Indexes and Queries 20-27

    Thesaurus

    Key Points

    The full-text thesaurus allows specifying synonyms or replacements for search terms. It is set up in a language-specific XML file for each SQL Server instance.

    Thesaurus

    The full-text thesaurus does not live within the database. It is an instance-level XML file that contains details of synonyms and replacement searches. There is one XML file per language per SQL Server instance. It is stored in the FTDATA folder that is located within the default database file folder for the instance.

    Expansion

    In the example shown in the slide, an expansion has been set up. Expansions are used for synonyms. In this example, SQL Server has been told that the words 'user', 'operator', and 'developer' can be used interchangeably. If a search is performed for any of these three words, a search is automatically performed for all three of the words.

    Replacement

    A replacement has also been created in the example shown in the slide. A replacement is used to provide alternate search terms. In the example shown, if the user searches for either the word 'NT5' or the word 'W2K', then a search for the word 'Windows 2000' would be carried out instead. Note that no search for 'NT5' or 'W2K' would actually be carried out. Only the replacement term would be searched for.

    Diacritic Sensitivity

    You may have noticed another option in the example thesaurus file in the slide. Diacritics are marks that are used as indicators in certain languages. These are uncommon in the English language today apart from when words have been adopted from another language. Many other languages use accents, breves,

  • 20-28 Implementing a Microsoft SQL Server 2008 R2 Database

    diaeresis, cedillas, etc. For example, the Greek language includes diacritics for breathings, stress and iota subscripts. Indic diacritics include the anusvara, chandrabindu, nukta, and virama.

    With the default value of zero for diacritics_sensitive, these are ignored. When the value is set to one, the search becomes sensitive to diacritics.

  • Working with Full-Text Indexes and Queries 20-29

    Stopwords and Stoplists

    Key Points

    Not all words in any language are useful in a word index. SQL Server automatically excludes common noise words from full-text indexes. These are referred to as stopwords. You can also configure other words to be ignored by full-text indexing. Stopwords are created within stoplists.

    Noise Words (Stopwords)

    Using English as an example, words such as 'and' or 'the' are not useful in an index. Similarly, in Simplified Chinese (language_id 2052), words such as '' (which means 'I') or '' (which means 'not') are not useful in an index. Each language, therefore, has a set of words that should be ignored when creating an index. You can see the list of system-supplied stopwords for all languages by executing the following query:

    SELECT * FROM sys.fulltext_system_stopwords;

    Stoplists and Stopwords

    In addition to the system-supplied stopwords, SQL Server allows you to define your own sets of stopwords. These are grouped together in stoplists.

    In the slide, a full-text stoplist called CompanyNames is being created and then the word 'Microsoft' is being added for language_id 1033 (English).

    The word 'Microsoft' would then no longer be indexed in full-text indexes within this database. You can see the list of stoplists that have been created by executing the following query:

    SELECT * FROM sys.fulltext_stoplists;

    You can see the user-defined stopwords by executing the following query:

    SELECT * FROM sys.fulltext_stopwords;

  • 20-30 Implementing a Microsoft SQL Server 2008 R2 Database

    SQL Server Management of Full-Text

    Key Points

    Full-text indexes live within the database that holds the tables they are based on. Like other indexes, they can benefit from periodic reorganization to remove fragmentation. Several useful DMVs have been provided for working with full-text indexing.

    Fragmentation

    Full-text indexes can become fragmented like other types of index. This can cause a loss of performance. The ALTER INDEX REORGANIZE command can be used to reorganize a full-text index to reduce fragmentation and increase performance.

    Changes to full-text indexes are not merged into the main index files immediately. Changes are first written to separate locations within the index. To perform a master merge or all full-text indexes in a full-text catalog, the ALTER FULLTEXT CATALOG REORGANIZE command can be used. A fully merged index will have higher performance.

    Dynamic Management Views and Functions

    Several dynamic management objects have been added to SQL Server to make it easier to troubleshoot full-text indexing. The views and functions are all prefixed with a sys.dm_fts* prefix.

    One particularly useful function is sys.dm_fts_parser. You can pass a string, a language id, and optionally a stoplist to this function. It will then display how it parses the string into words and how it categorizes those words into useful words or noise words. This can be very helpful when trying to work out how a character value is being indexed.

    Full-text indexing supports many document types without the need to install additional components. You can see the list of supported document types by executing the query:

    SELECT * FROM sys.fulltext_document_types;

  • Working with Full-Text Indexes and Queries 20-31

    This query returns a row for each supported document type.

  • 20-32 Implementing a Microsoft SQL Server 2008 R2 Database

    Demonstration 3A: Working with Full-Text Queries

    Key Points

    In this demonstration you will see how to:

    Query a full-text index.

    Locate the built-in stopwords.

    Create a stoplist and add a value to it.

    Check the parsing of text by the full-text engine.

    Demonstration Steps

    1. If Demonstration 1A was not performed:

    Revert the 623XB-MIA-SQL virtual machine using Hyper-V Manager on the host system.

    In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, click SQL Server Management Studio. In the Connect to Server window, type Proseware in the Server name text box and click Connect. From the File menu, click Open, click Project/Solution, navigate to D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ.ssmssln and click Open.

    Open and execute the 00 Setup.sql script file from within Solution Explorer.

    2. Open the 31 Demonstration 3A.sql script file. 3. Follow the instructions contained within the comments of the script file.

  • Working with Full-Text Indexes and Queries 20-33

    Lab 20: Working with Full-Text Indexes and Queries

    Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start.

    Right-click 623XB-MIA-DC and click Connect.

    In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears, and then close the Virtual Machine Connection window.

    4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started:

    Right-click 623XB-MIA-SQL and click Start.

    Right-click 623XB-MIA-SQL and click Connect.

    In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message appears.

    5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to

    complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item.

    Click Switch User, and then click Other User.

  • 20-34 Implementing a Microsoft SQL Server 2008 R2 Database

    Log on using the following credentials:

    i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check

    box and close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click

    SQL Server Management Studio. 11. In Connect to Server window, type Proseware in the Server name text box. 12. In the Authentication drop-down list box, select Windows Authentication and click Connect. 13. In the File menu, click Open, and click Project/Solution. 14. In the Open Project window, open the project

    D:\6232B_Labs\6232B_20_PRJ\6232B_20_PRJ.ssmssln. 15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click

    Execute on the toolbar.

    Lab Scenario

    Users have been complaining about the limited querying ability provided in the marketing system. You are intending to use full-text indexing to address these complaints.

    You will implement a full-text index on the Marketing.ProductDescription table to improve this situation.

    You will implement a stoplist to avoid excessive unnecessary index size.

    If you have time, your manager would like you to help provide a more natural interface for your users. This will involve creating a new stored procedure.

    Supporting Documentation Stored Procedure Specifications

    Name Marketing.GetRelevantDescriptions

    Input Parameters @PhraseToSearch nvarchar(1000)

    Output Parameters Nil

    Columns Returned ProductDescriptionID, Description, Ranking

    Provide relevant results by using the FREETEXTTABLE function and limit your results to rows with LanguageID = 'en' (for English).

  • Working with Full-Text Indexes and Queries 20-35

    Exercise 1: Implement a full-text index

    Scenario In this exercise, you will implement a full-text index on the Marketing.ProductDescription table to improve the searching abilities.

    The main tasks for this exercise are as follows:

    1. Create a full-text catalog. 2. Create a full-text index on the Description column of the Marketing.ProductDescription table. 3. Enable automatic change tracking for the index. 4. Check to see that the population of the index is complete. 5. Write a simple CONTAINS query. 6. Write a CONTAINS query that searches for two words. 7. Write a CONTAINS query that uses INFLECTIONAL forms.

    Task 1: Create a full-text catalog Execute T-SQL statements to create a new full-text catalog called DefaultFullTextCatalog.

    Ensure that the catalog is set as the default full-text catalog.

    Task 2: Create a full-text index on the Description column of the Marketing.ProductDescription table

    Execute T-SQL statements to create a full-text index on the Description column of the Marketing.ProductDescription table.

    Specify the primary key of the table as the key index.

    Initially configure change tracking and population off.

    Task 3: Enable automatic change tracking for the index Execute T-SQL statements to enable automatic change tracking for the table.

    Task 4: Check to see that the population of the index is complete Query the sys.fulltext_indexes system view to determine if the population is complete.

    Look in particular at the has_crawl_completed column.

    Task 5: Write a simple CONTAINS query Write a query to search for ProductDescriptionID and Description where the Description column

    contains the word bottle.

    Task 6: Write a CONTAINS query that searches for two words Write a query to search for ProductDescriptionID and Description where the Description column

    contains the words, elastic and lycra.

    Task 7: Write a CONTAINS query that uses INFLECTIONAL forms Write a query to search for ProductDescriptionID and Description where the Description column

    contains inflectional forms of the word wash.

    Results: After this exercise, you should have created and tested a full-text index.

  • 20-36 Implementing a Microsoft SQL Server 2008 R2 Database

    Exercise 2: Implement a stoplist

    Scenario In this exercise, you will implement a stoplist to avoid excessive unnecessary index size.

    The main tasks for this exercise are as follows:

    1. Review the existing system stopwords. 2. Create a full-text stoplist. 3. Add words to the stoplist. 4. View the stoplist.

    Task 1: Review the existing system stopwords Review the existing system stopwords by querying the view sys.fulltext_system_stopwords for

    language_id 1033. (English)

    Task 2: Create a full-text stoplist Create a full-text stoplist called CommonWords.

    Task 3: Add words to the stoplist Add the words, Bike and AdventureWorks to the stoplist for the English language.

    Task 4: View the stoplist View the new stoplist by querying the sys.fulltext_stoplists and sys.fulltext_stopwords views.

    Results: After this exercise, you should have created a new stoplist that will help avoid excessive index size growth.

  • Working with Full-Text Indexes and Queries 20-37

    Challenge Exercise 3: Create a stored procedure to implement a full-text search (Only if time permits) Scenario

    In this exercise, you want to provide a more natural interface for your users. In this exercise, you will create a stored procedure that implements a more advanced type of search.

    The main tasks for this exercise are as follows:

    1. Review the supporting documentation. 2. Design, implement, and test the stored procedure.

    Task 1: Review the supporting documentation The supporting documentation includes specifications for the design of a new stored procedure.

    Task 2: Design, implement, and test the stored procedure Design and implement the stored procedure. The procedure Marketing.GetRelevantDescriptions takes

    an input search term and returns the specified columns from the Marketing.ProductDescription table. Rows are returned where they are considered relevant, based on the FREETEXTTABLE function and the English language.

    Test the stored procedure using the search phrases 'strong frame' and 'serious competition'.

    Results: After this exercise, you should have created a new stored procedure and tested its behavior.

  • 20-38 Implementing a Microsoft SQL Server 2008 R2 Database

    Module Review and Takeaways

    Review Questions

    1. What is the function of a stopword? 2. What are iFilters used for? 3. What is the difference between FREETEXT and FREETEXTTABLE? 4. How do you configure a thesaurus for use with full-text indexing?

    Best Practices

    1. Create a stoplist for your company. Add to the stoplist, any words that are used in almost all your company documents.

    2. Use auto-population of indexes except in rare cases with specific issues. (These situations would typically involve data that is updated at a high rate and where the index does not need to be kept completely up to date).

    3. Try to encourage developers in your organization to offer much more flexible user interfaces to your end users, based on full-text indexes in SQL Server.

  • Working with Full-Text Indexes and Queries 20-39

    Course Review and Evaluation

  • 20-40 Implementing a Microsoft SQL Server 2008 R2 Database

  • Lab: Introduction to SQL Server and its Toolset L1-1

    Module 1: Introduction to SQL Server 2008 R2 and its Toolset

    Lab: Introduction to SQL Server and its Toolset Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears, and then close the Virtual Machine Connection window.

    4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL1 is not started:

    Right-click 623XB-MIA-SQL1 and click Start. Right-click 623XB-MIA-SQL1 and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears.

    5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

    User name: AdventureWorks\Administrator Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and

    close the Server Manager window.

    Exercise 1: Verify SQL Server Component Installation

    Task 1: Check that Database Engine and Reporting Services have been installed for the MKTG instance 1. Click Start, click All Programs, click Microsoft SQL Server 2008 R2, click Configuration Tools, and

    then click SQL Server Configuration Manager.

    2. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    3. In the right-hand pane, ensure that the following services are listed for the MKTG instance:

    SQL Server (MKTG)

    SQL Full-text Filter Daemon Launcher (MKTG)

    SQL Server Reporting Services (MKTG)

    SQL Server Agent (MKTG)

  • L1-2 Lab: Introduction to SQL Server and its Toolset

    Note: The SQL Full-text Filter Daemon Launcher is present and it is part of the Database Engine.

    Task 2: Note the services that are installed for the default instance and that Integration Services is not installed on a per instance basis 1. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    2. In the right-hand pane, ensure that the following services are listed for the default instance:

    SQL Server (MSSQLSERVER)

    SQL Full-text Filter Daemon Launcher (MSSQLSERVER)

    SQL Server Analysis Services (MSSQLSERVER)

    SQL Server Agent (MSSQLSERVER)

    3. In the right-hand pane, note that SQL Server Integration Services 10.0 is not installed as a per-instance basis as there is no instance name shown.

    Task 3: Ensure that all required services including SQL Server Agent are started and set to autostart for both instances 1. Check that all the services for the MKTG instance have a Start Mode of Automatic. Ignore the SQL

    Full-text Filter Daemon Launcher service at this time.

    Note: The SQL Server Agent (MKTG) service is not set to autostart.

    2. Right-click the SQL Server Agent (MKTG) service and click Properties.

    3. In the Log On tab, click Start and the SQL Server Agent service should start.

    4. In the Service tab, set the value for the Start Mode to Automatic, and then click OK.

    5. Check that all the services for the default instance have a Start Mode of Automatic. Ignore the SQL Full-text Filter Daemon Launcher service at this time.

    6. Check that the SQL Server Agent (MSSQLSERVER) service has Start Mode set to Automatic.

    Note: The SQL Server Agent (MSSQLSERVER) service is not set to autostart.

    7. Right-click the SQL Server Agent (MSSQLSERVER) service and click Properties.

    8. In the Log On tab, click Start and the SQL Server Agent service should start.

  • Lab: Introduction to SQL Server and its Toolset L1-3

    9. In the Service tab, set the value for the Start Mode to Automatic, and then click OK.

    10. The SQL Server Services need to be configured as the screenshot below:

    Exercise 2: Alter Service Accounts for New Instance

    Task 1: Change the service account for the MKTG database engine 1. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    2. In the right-hand pane, right-click SQL Server (MTKG), and select Properties.

    3. In the Account Name text box, type AdventureWorks\PWService.

    4. In the Password text box, type Pa$$w0rd.

    5. In the Confirm Password text box, type Pa$$w0rd and click OK.

    6. In the Confirm Account Change window, click Yes.

    Task 2: Change the service account for the MKTG SQL Server Agent 1. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    2. In the right-hand pane, right-click SQL Server Agent (MTKG), and select Properties.

    3. In the Account Name text box, type

    AdventureWorks\PWService. 4. In the Password text box, type Pa$$w0rd.

    5. In the Confirm Password text box, type Pa$$w0rd and click OK.

    6. Right-click SQL Server Agent (MTKG) and select Start to restart the service.

    Exercise 3: Enable Named Pipes Protocol for Both Instances

    Task 1: Enable the named pipes protocol for the default instance 1. In the left-hand pane of the SQL Server Configuration Manager window, expand SQL Server

    Network Configuration and then click Protocols for MSSQLSERVER.

    2. In the right-hand pane, right-click Named Pipes and select Enable.

    3. In the Warning window, click OK.

    Task 2: Enable the named pipes protocol for the MKTG instance 1. In the left-hand pane of the SQL Server Configuration Manager window, click Protocols for

    MKTG.

  • L1-4 Lab: Introduction to SQL Server and its Toolset

    2. In the right-hand pane, right-click Named Pipes and select Enable.

    3. In the Warning window, click OK.

    Task 3: Restart both database engine services 1. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    2. Right-click SQL Server (MSSQLSERVER) and select Restart.

    3. Right-click SQL Server (MKTG) and select Restart.

    4. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    5. In the toolbar, click the Refresh icon.

    Exercise 4: Create Aliases for AdventureWorks and Proseware

    Task 1: Create a 32-bit alias (AdventureWorks) for the default instance 1. In the left-hand pane of the SQL Server Configuration Manager window, expand SQL Native

    Client 10.0 Configuration (32bit) and click Client Protocols.

    2. Confirm that the Named Pipes protocol is Enabled.

    3. In the left-hand pane, right-click Aliases and select New Alias.

    4. In the Alias New window, in the Alias Name text box, type AdventureWorks.

    5. In the Protocol drop-down list box, select Named Pipes.

    6. In the Server text box, type . and click OK.

    Task 2: Create a 32-bit alias (Proseware) for the MKTG instance 1. In the left-hand pane of the SQL Server Configuration Manager window, expand SQL Native

    Client 10.0 Configuration (32bit) and click Client Protocols.

    2. Confirm that the Named Pipes protocol is Enabled.

    3. In the left-hand pane, right-click Aliases and select New Alias.

    4. In the Alias New window, in the Alias Name text box, type Proseware.

    5. In the Protocol drop-down list box, select Named Pipes.

    6. In the Server text box, type .\MKTG and click OK.

    Task 3: Create a 64-bit alias (AdventureWorks) for the default instance 1. In the left-hand pane of the SQL Server Configuration Manager window, expand SQL Native

    Client 10.0 Configuration and click Client Protocols.

    2. Confirm that the Named Pipes protocol is Enabled.

    3. In the left-hand pane, right-click Aliases and select New Alias.

    4. In the Alias New window, in the Alias Name text box, type AdventureWorks.

    5. In the Protocol drop-down list box, select Named Pipes.

    6. In the Server text box, type . and click OK.

    Task 4: Create a 64-bit alias (Proseware) for the MKTG instance 1. In the left-hand pane of the SQL Server Configuration Manager window, expand SQL Native

    Client 10.0 Configuration and click Client Protocols.

  • Lab: Introduction to SQL Server and its Toolset L1-5

    2. Confirm that the Named Pipes protocol is Enabled.

    3. In the left-hand pane, right-click Aliases and select New Alias.

    4. In the Alias New window, in the Alias Name text box, type Proseware.

    5. In the Protocol drop-down list box, select Named Pipes.

    6. In the Server text box, type .\MKTG and click OK.

    Task 5: Use SQL Server Management Studio to connect to both aliases to ensure they work as expected 1. Click Start, click All Programs, click Microsoft SQL Server 2008 R2, and then click SQL Server

    Management Studio.

    2. In the Connect to Server window, ensure that Server Type is set to Database Engine.

    3. In the Server name text box, type Proseware.

    4. In the Authentication drop-down list, select Windows Authentication, and click Connect.

    5. In Object Explorer, under Proseware expand Databases.

    Note: The databases that are present include at least the following: System Databases, Database Snapshots, ReportServer$MKTG, and ReportServer$MKTGTempDB.

    6. In Object Explorer, click Connect, click Database Engine.

    7. In the Connect to Server window, ensure that Server Type is set to Database Engine.

    8. In the Server name text box, type AdventureWorks.

    9. In the Authentication drop-down list, select Windows Authentication, and click Connect.

    10. In Object Explorer, under AdventureWorks expand Databases.

    Note: The databases that are present include at least the following: System Databases, Database Snapshots, AdventureWorks2008R2, and AdventureWorksDW2008R2.

    11. Close SQL Server Management Studio.

    12. Close SQL Server Configuration Manager.

    Challenge Exercise 5: Ensure SQL Browser is Disabled and Configure a Fixed TCP/IP Port (Only if time permits)

    Task 1: Configure the TCP port for the MKTG database engine instance to 51550 1. In the Virtual Machine window, click Start.

    2. From the Start menu, click All Programs, click Microsoft SQL Server 2008 R2, click Configuration Tools, and then click SQL Server Configuration Manager.

    3. In the left-hand pane of the SQL Server Configuration Manager window, expand SQL Server Network Configuration and then click Protocols for MKTG.

    4. Right-click the TCP/IP protocol and select Properties.

    5. In the TCP/IP Properties window, click IP Addresses tab.

    6. Scroll to the bottom of the screen, under the IPAll section, clear the value for TCP Dynamic Ports.

  • L1-6 Lab: Introduction to SQL Server and its Toolset

    7. For TCP Port, type 51550, and click OK.

    8. In the Warning window, click OK.

    9. In the left-hand pane, click SQL Server Services.

    10. Right-click SQL Server (MKTG) and select Restart.

    11. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    12. In the toolbar, click the Refresh icon and make sure the service starts.

    Task 2: Disable the SQLBrowser service 1. In the left-hand pane of the SQL Server Configuration Manager window, click SQL Server Services.

    2. In the right-hand pane, right-click SQL Server Browser and click Stop.

    3. Right-click the SQL Server Browser and click Properties.

    4. In the SQL Server Browser Properties window, in the Service tab, set the Start Mode to Disabled and click OK.

  • Lab: Working with Data Types L2-1

    Module 2: Working with Data Types

    Lab: Working with Data Types Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears, and then close the Virtual Machine Connection window. 4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started:

    Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears. 5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

    i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and

    close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL

    Server Management Studio.

    11. In Connect to Server window, type Proseware in the Server name text box.

    12. In the Authentication drop-down list box, select Windows Authentication and click Connect.

    13. In the File menu, click Open, and click Project/Solution.

    14. In the Open Project window, open the project D:\6232B_Labs\6232B_02_PRJ\6232B_02_PRJ.ssmssln.

    15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

    Exercise 1: Choosing Appropriate Data Types

    Task 1: Determine column names and data types 1. Review the supporting documentation for details of the PhoneCampaign, Opportunity and

    SpecialOrder tables and determine column names, data types, and nullability for each data item in the design.

  • L2-2 Lab: Working with Data Types

    Note: With any design exercise, there is no one correct answer. A sample solution has been provided below.

    Table 1: PhoneCampaign

    Description Column Name and Data Type

    Which campaign this relates to. PhoneCampaignID INT NOT NULL

    The prospect that was contacted. ProspectID INT NOT NULL

    When contact was first attempted with the prospect. FirstAttemptedContact DATETIME NULL

    Comments related to the contact that was made, if it was made.

    ContactComments NVARCHAR(MAX) NULL

    When contact was actually made with the prospect. InitialContact DATETIME NULL

    Outcome of the contact: sale, later follow-up or no interest

    ContactOutcomeCode CHAR(1) NULL

    Value of any sale made (up to 2 decimal places) SalesValue DECIMAL(10,2) NULL

    Table 2: Opportunity

    Description Column Name and Data Type

    Name of the opportunity OpportunityID INT NOT NULL

    Which prospect this opportunity relates to ProspectID INT NOT NULL

    Stage the sale is at: Lead, Qualification, Proposal Development, Contract Negotiations, Complete, Lost

    SalesStageCode CHAR(2) NOT NULL

    Date that the opportunity was raised DateRaised DATETIME NOT NULL

    Probability of success Likelihood TINYINT NOT NULL

    Rating: Cold, Warm, Hot Rating CHAR(1) NOT NULL

    Estimated closing date EstimatedClosingDate DATE NOT NULL

    Estimated revenue EstimatedRevenue DECIMAL(10,2) NOT NULL

    Delivery address DeliveryAddress NVARCHAR(MAX) NOT NULL

    Table 3: SpecialOrder

    Description Column Name and Data Type

    Which prospect this order is for ProspectID INT NOT NULL

  • Lab: Working with Data Types L2-3

    Description Column Name and Data Type

    External supplier of the item SupplierID INT NOT NULL

    Description of the item ItemDescription NVARCHAR(100) NOT NULL

    Quantity Required (some quantities are whole numbers, some are fractional with up to 3 decimal places)

    QuantityRequired DECIMAL(10,3) NOT NULL

    Date of order OrderDate DATETIME NOT NULL

    Promised delivery date PromisedDeliveryDate DATE NOT NULL

    Actual delivery date ActualDeliveryDate DATE NULL

    Special requirements (any comments related to the special order)

    SpecialRequirements NVARCHAR(MAX) NULL

    Quoted price per unit (up to 2 decimal places) QuotedPricePerUnit DECIMAL(10,2) NOT NULL

    Exercise 2: Writing Queries With Data Type Conversions

    Task 1: Connect to the MarketDev Database 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    Task 2: Review the first query requirement and write a SELECT statement to meet the requirement 1. Review the supporting documentation for details for the first query requirement.

    2. In Object Explorer, expand the Databases under Proseware.

    3. Right-click the MarketDev database and click New Query.

    4. Type the query below in the query pane:

    SELECT ProductID, ProductName, CONVERT(varchar(8),SellEndDate,112) AS SellEndDate FROM Marketing.Product; GO

    5. In the toolbar, click Execute.

    6. Ensure that the results from the query match the required output as shown in the supporting documentation.

    Task 3: Review the second query requirement and write a SELECT statement to meet the requirement 1. Review the supporting documentation for details for the second query requirement.

    2. In Object Explorer, expand the Databases under Proseware.

  • L2-4 Lab: Working with Data Types

    3. Right-click the MarketDev database and click New Query.

    4. Type the query below in the query pane:

    SELECT ProspectID, CAST(Demographics AS nvarchar(1000)) AS Demographics FROM Marketing.Prospect; GO

    5. In the toolbar, click Execute.

    6. Ensure that the results from the query match the required output as shown in the supporting documentation.

    Challenge Exercise 3: Designing and Creating Alias Data Types (Only if time permits)

    Task 1: Investigate the storage of phone numbers and email addresses 1. In the Object Explorer, expand Databases, and expand MarketDev, and expand Tables.

    2. In each table, expand Columns, noting any columns that are holding details of Phone Numbers or Email Addresses. The following columns should be identified:

    Table Phone Number Columns Definition

    Marketing.Prospect CellPhoneNumber NVARCHAR(20)

    Marketing.Prospect HomePhoneNumber NVARCHAR(25)

    Marketing.Prospect WorkPhoneNumber VARCHAR(22)

    Table Email Address Columns Definition

    Marketing.Prospect EmailAddress NVARCHAR(100)

    Marketing.SalesPerson EmailAlias NVARCHAR(256)

    Task 2: Create a data type that stores phone numbers 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE TYPE PhoneNumber FROM nvarchar(25); GO

    4. In the toolbar, click Execute.

    Task 3: Create a data type that stores email addresses 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

  • Lab: Working with Data Types L2-5

    3. Type the query below in the query pane:

    CREATE TYPE EmailAddress FROM nvarchar(256); GO

    4. In the toolbar, click Execute

  • L2-6 Lab: Working with Data Types

  • Lab: Designing and Implementing Tables L3-1

    Module 3: Designing and Implementing Tables

    Lab: Designing and Implementing Tables Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears, and then close the Virtual Machine Connection window. 4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started:

    Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears. 5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

    i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and

    close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL

    Server Management Studio.

    11. In Connect to Server window, type Proseware in the Server name text box.

    12. In the Authentication drop-down list box, select Windows Authentication and click Connect.

    13. In the File menu, click Open, and click Project/Solution.

    14. In the Open Project window, open the project D:\6232B_Labs\6232B_03_PRJ\6232B_03_PRJ.ssmssln.

    15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

    Exercise 1: Improve the Design of Tables

    Task 1: Review the supplied design 1. Review the supplied design in the supporting documentation for the exercise.

    Task 2: Suggest an improved design

    Note: With any design exercise, there is no one correct answer. A sample solution has been provided below.

  • L3-2 Lab: Designing and Implementing Tables

    Table1: Competitor (Table name change to singular to match existing singular table names in the database)

    Name Data Type Design Rationale

    CompetitorID INT

    NOT NULL

    Prefer numeric code for surrogate keys

    CompetitorName NVARCHAR(30) NOT NULL

    The column name Name is too generic

    Unicode data type for flexibility

    StreetAddress NVARCHAR(max) NOT NULL

    Common to have multiple addresses

    Unicode data type for flexibility

    DateEntered DATE NOT NULL

    Removed underscore for consistency

    Chose appropriate data type

    StrengthOfCompetition

    NVARCHAR(8) NOT NULL

    Renamed for consistency

    Note: Suspect this should be a code or a number but would require more information from Business Analyst

    Unicode data type for flexibility

    Comments NVARCHAR(max) NULL Unicode data type for flexibility

    NULL because there may be no comments

    Table2A: City (Duplicated City details extracted from the original table called TVAdvertisements)

    Name Data Type Design Rationale

    CityID INT

    NOT NULL

    Added a surrogate key

    CityName NVARCHAR(25) NOT NULL

    Renamed original column

    Retained data type where no further information is available

    Table2B: TVStation (Duplicated TV Station details extracted from the original table called TVAdvertisements)

    Name Data Type Design Rationale

    TVStationID INT NOT NULL

    Added a surrogate key

    TVStationName NVARCHAR(15) NOT NULL

    Renamed original column

    Retained data type where no further information is available

  • Lab: Designing and Implementing Tables L3-3

    Name Data Type Design Rationale

    CityID INT NOT NULL

    City details extracted to a separate table

    CostPerAdvertisement DECIMAL(12,2) NOT NULL

    Chose appropriate data type

    TotalCostOfAllAdvertisements removed as it should be calculated

    NumberOfAdvertisements removed as it should be calculated

    Table2C: TVAdvertisement (Extracted repeating groups from the original table called TVAdvertisements)

    Name Data Type Design Rationale

    TVAdvertisementID INT NOT NULL

    Added a surrogate key

    TVStationID INT NOT NULL

    Reference to TV Station table

    ScreeningTime DATETIME NOT NULL

    Single data type to hold both values

    Name to reflect combination of values

    Table3: CampaignResponse (Table name change to singular to match existing singular table names in the database and removed underscore for consistency)

    Name Data Type Design Rationale

    TVAdvertisementID INT NOT NULL

    Added a surrogate key

    ResponseReceived DATETIME NOT NULL

    Improved column name

    ProspectID INT NOT NULL

    Reference to existing Prospect table

    ResponseMethodCode CHAR(1) NOT NULL

    Changed to a straightforward code using first letter

    An alternative would be to extract the response method as another lookup table

    ChargeFromReferrer DECIMAL(12,2) NOT NULL

    Chose appropriate data type

    RevenueReceived DECIMAL(12,2) NOT NULL

    Chose appropriate data type

    ResponseProfit should be removed as it should be calculated rather than stored in the table

  • L3-4 Lab: Designing and Implementing Tables

    Exercise 2: Create a Schema

    Task 1: Connect to the MarketDev Database 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    Task 2: Create a schema named DirectMarketing 1. Type the query below in the query pane:

    CREATE SCHEMA DirectMarketing AUTHORIZATION dbo; GO

    2. In the toolbar, click Execute.

    Challenge Exercise 3: Create the Tables (Only if time permits)

    Task 1: Create the tables 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    Note: The sample query below is based on the sample solution. Your query should be based on your design. The solution shown below is contained in the 71 Lab Exercise 3.sql script file in Solution Explorer.

    CREATE TABLE DirectMarketing.Competitor ( CompetitorID INT NOT NULL PRIMARY KEY, CompetitorName NVARCHAR(30) NOT NULL, StreetAddress NVARCHAR(MAX) NOT NULL, DateEntered DATE NOT NULL, StrengthOfCompetition NVARCHAR(8) NOT NULL, Comments NVARCHAR(MAX) NULL ); GO CREATE TABLE DirectMarketing.City ( CityID INT NOT NULL PRIMARY KEY, CityName NVARCHAR(25) NOT NULL ); GO CREATE TABLE DirectMarketing.TVStation ( TVStationID INT NOT NULL PRIMARY KEY, TVStationName NVARCHAR(15) NOT NULL, CityID INT NOT NULL, CostPerAdvertisement DECIMAL(12,2) NOT NULL ); GO CREATE TABLE DirectMarketing.TVAdvertisement ( TVAdvertisementID INT NOT NULL PRIMARY KEY, TVStationID INT NOT NULL, ScreeningTime DATETIME NOT NULL ); GO

  • Lab: Designing and Implementing Tables L3-5

    CREATE TABLE DirectMarketing.CampaignResponse ( CampaignResponseID INT NOT NULL PRIMARY KEY, ResponseReceived DATETIME NOT NULL, ProspectID INT NOT NULL, ResponseMethodCode CHAR(1) NOT NULL, ChargeFromReferrer DECIMAL(12,2) NOT NULL, RevenueReceived DECIMAL(12,2) NOT NULL ); GO

    4. In the toolbar, click Execute.

  • L3-6 Lab: Designing and Implementing Tables

  • Lab: Designing and Implementing Views L4-1

    Module 4: Designing and Implementing Views

    Lab: Designing and Implementing Views Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears, and then close the Virtual Machine Connection window. 4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started:

    Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears. 5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

    i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and

    close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL

    Server Management Studio.

    11. In Connect to Server window, type Proseware in the Server name text box.

    12. In the Authentication drop-down list box, select Windows Authentication and click Connect.

    13. In the File menu, click Open, and click Project/Solution.

    14. In the Open Project window, open the project D:\6232B_Labs\6232B_04_PRJ\6232B_04_PRJ.ssmssln.

    15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

    Exercise 1: Design, Implement and Test the WebStock Views

    Task 1: Create the WebStock schema 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE SCHEMA WebStock AUTHORIZATION dbo; GO

  • L4-2 Lab: Designing and Implementing Views

    4. In the toolbar, click Execute.

    Task 2: Review the design requirements 1. Review the supplied design in the supporting documentation for the OnlineProducts and

    AvailableModels views.

    Task 3: Design and implement the views 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    CREATE VIEW WebStock.OnlineProducts AS SELECT p.ProductID, p.ProductName, p.ProductNumber, COALESCE(p.Color,'N/A') AS Color, CASE p.DaysToManufacture WHEN 0 THEN 'Instock' WHEN 1 THEN 'Overnight' WHEN 2 THEN 'Fast' ELSE 'Call' END AS Availability, p.Size, p.SizeUnitMeasureCode AS UnitOfMeasure, p.ListPrice AS Price, p.Weight FROM Marketing.Product AS p WHERE p.SellEndDate IS NULL AND p.SellStartDate IS NOT NULL; GO CREATE VIEW WebStock.AvailableModels AS SELECT p.ProductID, p.ProductName, pm.ProductModelID, pm.ProductModel FROM Marketing.Product AS p INNER JOIN Marketing.ProductModel AS pm ON p.ProductModelID = pm.ProductModelID WHERE p.SellEndDate IS NULL AND p.SellStartDate IS NOT NULL; GO

    3. In the toolbar, click Execute.

    Task 4: Test the views 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    SELECT * FROM WebStock.OnlineProducts; GO SELECT * FROM WebStock.AvailableModels; GO

    3. In the toolbar, click Execute.

  • Lab: Designing and Implementing Views L4-3

    Exercise 2: Design and Implement the Contacts View

    Task 1: Create the Relationship schema 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE SCHEMA Relationship AUTHORIZATION dbo; GO

    4. In the toolbar, click Execute.

    Task 2: Review the design requirements 1. Review the supplied design in the supporting documentation for the Contacts view.

    Task 3: Design and implement the view 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    CREATE VIEW Relationship.Contacts AS SELECT p.ProspectID AS ContactID, p.FirstName, p.MiddleName, p.LastName, 'PROSPECT' AS ContactRole FROM Marketing.Prospect AS p UNION ALL SELECT sp.SalespersonID, sp.FirstName, sp.MiddleName, sp.LastName, 'SALESPERSON' FROM Marketing.Salesperson AS sp; GO

    3. In the toolbar, click Execute.

    Task 4: Test the view 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    SELECT * FROM Relationship.Contacts; GO

    3. In the toolbar, click Execute.

    Challenge Exercise 3: Modify the AvailableModels View (Only if time permits)

    Task 1: Alter the AvailableModels View 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

  • L4-4 Lab: Designing and Implementing Views

    ALTER VIEW WebStock.AvailableModels AS SELECT p.ProductID, p.ProductName, pm.ProductModelID, pm.ProductModel, COALESCE(ed.Description,id.Description) AS CatalogDescription FROM Marketing.Product AS p INNER JOIN Marketing.ProductModel AS pm ON p.ProductModelID = pm.ProductModelID LEFT OUTER JOIN Marketing.ProductDescription AS ed ON pm.ProductModelID = ed.ProductModelID AND ed.LanguageID = 'en' LEFT OUTER JOIN Marketing.ProductDescription as id ON pm.ProductModelID = id.ProductModelID AND id.LanguageID = '' WHERE p.SellEndDate IS NULL AND p.SellStartDate IS NOT NULL; GO

    3. In the toolbar, click Execute.

    Task 2: Test the view 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    SELECT * FROM WebStock.AvailableModels; GO

    3. In the toolbar, click Execute.

    4. This page intentionally left blank

  • Lab: Planning for SQL Server Indexing L5-1

    Module 5: Planning for SQL Server 2008 R2 Indexing

    Lab: Planning for SQL Server Indexing Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears, and then close the Virtual Machine Connection window.4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started:

    Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to logon message

    appears. 5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

    i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and

    close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL

    Server Management Studio.

    11. In Connect to Server window, type Proseware in the Server name text box.

    12. In the Authentication drop-down list box, select Windows Authentication and click Connect.

    13. In the File menu, click Open, and click Project/Solution.

    14. In the Open Project window, open the project D:\6232B_Labs\6232B_05_PRJ\6232B_05_PRJ.ssmssln.

    15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

    Exercise 1: Explore existing index statistics

    Task 1: Execute SQL Command 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

  • L5-2 Lab: Planning for SQL Server Indexing

    3. Type the query below in the query pane:

    EXEC sp_helpstats Marketing.Product GO

    4. In the toolbar, click Execute.

    Task 2: Review the results 1. In the Query Analyzer Results pane, review the results.

    2. Check to see if any autostats has been generated. If any autostats have been created, they will appear in the results with an _WA prefix.

    Task 3: Create statistics 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    CREATE STATISTICS Product_Color_Stats ON Marketing.Product (Color) WITH FULLSCAN; GO

    3. In the toolbar, click Execute.

    Task 4: Re-execute the SQL command from task 1 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    EXEC sp_helpstats Marketing.Product GO

    3. In the toolbar, click Execute.

    Task 5: Use DBCC SHOW_STATISTICS 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    DBCC SHOW_STATISTICS('Marketing.Product',Product_Color_Stats); GO

    3. In the toolbar, click Execute.

    Task 6: Answer questions 1. Complete the answer column in the table below.

    Note: The results returned can vary. Sample results are shown in the following table

  • Lab: Planning for SQL Server Indexing L5-3

    Question Answer

    How many rows were sampled? 504

    How many steps were created? 10

    What was the average key length? 5.178571

    How many Black products are there? 93

    Task 7: Execute SQL Command and check accuracy of statistics 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    SELECT COUNT(1) FROM Marketing.Product WHERE Color = 'Black'; GO

    3. In the toolbar, click Execute.

    Task 8: Calculate Selectivity of each query 1. Right-click the MarketDev database and click New Query.

    2. Type the query below in the query pane:

    -- Calculate the total number of rows in the table SELECT COUNT(1) FROM Marketing.Prospect; GO

    3. In the toolbar, click Execute.

    Note: A sample result would be 19955

    4. Type the query below in the same query pane:

    -- Query 1 SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'A%'; GO

    5. Highlight only Query 1 and click Execute.

    6. Calculate the selectivity of the query.

    Note: A sample result would be 2013 / 19955 or approximately 10.1%

    7. Type the query below in the same query pane:

    -- Query 2 SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Alejandro%';

  • L5-4 Lab: Planning for SQL Server Indexing

    GO

    8. light only Query 2 and click Execute.

    955 or approximately 0.2%

    High

    9. Calculate the selectivity of the query.

    Note: A sample result would be 48 / 19

    10. Type the query below in the same query pane:

    -- Query 3 SELECT ProspectID, FirstName, LastName FROM Marketing.Prospect WHERE FirstName LIKE 'Arif%'; GO

    11. ly Query 3 and click Execute.

    55 or approximately 0.0%

    Highlight on

    12. Calculate the selectivity of the query.

    Note: A sample result would be 1 / 199

    Challeng Only if time permits)

    1. Review the supporting documentation for Query 1, the columns and column order is detailed in the

    e Exercise 2: Design column orders for indexes (

    Task 1: Design an index

    table below:

    Columns Column Order

    ProspectID 1

    Rationale: Selecting by ProspectID onl nd no output order y a

    Task1. Review the supporting documentation for Query 2, the columns and column order is detailed in the

    2: Design an index

    table below:

    Columns Column Order

    FirstName 1

    Rationale: Selecting by FirstName only d no output order an

    Task1. Review the supporting documentation for Query 3, the columns and column order is detailed in the

    3: Design an index

    table below:

  • Lab: Planning for SQL Server Indexing L5-5

    Columns Column Order

    FirstName 1

    LastName 2

    Rationale: Selecting only a single FirstName. Adding LastName to the index will supply the correct output order

    Task 4: Design an index 1. Review the supporting documentation for Query 4, the columns and column order is detailed in the

    table below:

    Columns Column Order

    FirstName 1

    LastName 2

    Rationale: Selecting a range of FirstNames could have varying selectivity. In this case, the selectivity of the FirstName column is sufficient to warrant the index on the FirstName. Note that if the constant was an A rather than an S, the index would be better defined as LastName, FirstName instead

    Task 5: Design an index 1. Review the supporting documentation for Query 5, the columns and column order is detailed in the

    table below:

    Columns Column Order

    LanguageID 1

    Rationale: Grouping by LanguageID. Note that in this case an alternate output order would not change the recommendation

  • L5-6 Lab: Planning for SQL Server Indexing

  • Lab: Implementing Table Structures in SQL Server L6-1

    Module 6: Implementing Table Structures in SQL Server 2008 R2

    Lab: Implementing Table Structures in SQL Server Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears, and then close the Virtual Machine Connection window.4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started:

    Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to logon message

    appears. 5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

    i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and

    close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL

    Server Management Studio.

    11. In Connect to Server window, type Proseware in the Server name text box.

    12. In the Authentication drop-down list box, select Windows Authentication and click Connect.

    13. In the File menu, click Open, and click Project/Solution.

    14. In the Open Project window, open the project D:\6232B_Labs\6232B_06_PRJ\6232B_06_PRJ.ssmssln.

    15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

    Exercise 1: Creating Tables as Heaps

    Task 1: Review the Requirements 1. Review the supporting documentation for Table 1 and 2.

  • L6-2 Lab: Implementing Table Structures in SQL Server

    Task 2: Create the Tables in the MarketDev database 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE TABLE Relationship.ActivityLog ( ActivityTime datetimeoffset, SessionID int, Duration int, ActivityType int ); GO CREATE TABLE Relationship.PhoneLog ( PhoneLogID int PRIMARY KEY NONCLUSTERED, SalespersonID int, CalledPhoneNumber nvarchar(16), CallDurationSeconds int ); GO

    4. In the toolbar, click Execute.

    Exercise 2: Creating Tables with Clustered Indexes

    Task 1: Review the Requirements 1. Review the supporting documentation for Tables 3 and 4.

    Task 2: Create the Tables in the MarketDev database 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE TABLE Relationship.MediaOutlet ( MediaOutletID int PRIMARY KEY CLUSTERED, MediaOutletName nvarchar(40), PrimaryContact nvarchar(50), City nvarchar(50) ); GO CREATE TABLE Relationship.PrintMediaPlacement ( PrintMediaPlacementID int PRIMARY KEY CLUSTERED, MediaOutletID int, PlacementDate datetime, PublicationDate datetime, RelatedProductID int, PlacementCost decimal(18,2) ); GO

    4. In the toolbar, click Execute.

  • Lab: Implementing Table Structures in SQL Server L6-3

    Challenge Exercise 3: Comparing the Performance of Clustered Indexes vs. Heaps (Only if time permits)

    Task 1: Review the Table Design 1. Review the supporting documentation for Table 5.

    Task 2: Create the Relationship.Table_Heap Table 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE TABLE Relationship.Table_Heap ( ApplicationID int IDENTITY(1,1), ApplicantName nvarchar(150), EmailAddress nvarchar(100), ReferenceID uniqueidentifier, Comments nvarchar(500) ); GO

    4. In the toolbar, click Execute.

    Task 3: Create the Relationship.Table_ApplicationID Table 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE TABLE Relationship.Table_ApplicationID ( ApplicationID int IDENTITY(1,1), ApplicantName nvarchar(150), EmailAddress nvarchar(100), ReferenceID uniqueidentifier, Comments nvarchar(500) ); GO CREATE CLUSTERED INDEX IX_ApplicantID ON Relationship.Table_ApplicationID (ApplicationID); GO

    4. In the toolbar, click Execute.

    Task 4: Create the Relationship.Table_EmailAddress Table 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE TABLE Relationship.Table_EmailAddress ( ApplicationID int IDENTITY(1,1),

  • L6-4 Lab: Implementing Table Structures in SQL Server

    ApplicantName nvarchar(150), EmailAddress nvarchar(100), ReferenceID uniqueidentifier, Comments nvarchar(500) ); GO CREATE CLUSTERED INDEX IX_EmailAddress ON Relationship.Table_EmailAddress (EmailAddress); GO

    4. In the toolbar, click Execute.

    Task 5: Create the Relationship.Table_ReferenceID Table 1. In Object Explorer, expand the Databases under Proseware.

    2. Right-click the MarketDev database and click New Query.

    3. Type the query below in the query pane:

    CREATE TABLE Relationship.Table_ReferenceID ( ApplicationID int IDENTITY(1,1), ApplicantName nvarchar(150), EmailAddress nvarchar(100), ReferenceID uniqueidentifier, Comments nvarchar(500) ); GO CREATE CLUSTERED INDEX IX_ReferenceID ON Relationship.Table_ReferenceID (ReferenceID); GO

    4. In the toolbar, click Execute.

    Task 6: Load and Execute the Workload Script 1. In Solution Explorer, double-click the file 72 Lab Exercise 3 Workload Script.sql.

    2. In the toolbar, click Execute.

    Note: this may take approximately five minutes to complete, depending on available hardware resources. You can check where it is up to by periodically switching to the Messages tab. A message is printed as each of the four sections is completed. While the script is running, review the contents of the script and estimate the proportion of time difference you expect to see in the results.

    Task 7: Compare Table Performance 1. Compare the performance of each table structure as reported by the results of executing the

    Workload script.

    Note: Results will vary substantially depending upon the hardware the Virtual Machine is running on. Sample results are shown below.

    HeapTime ApplicationIDTime EmailAddressTime ReferenceIDTime

    23 seconds 21 seconds 91 seconds 134 seconds

  • Lab: Reading SQL Server Execution Plans L7-1

    Module 7: Reading SQL Server 2008 R2 Execution Plans

    Lab: Reading SQL Server Execution Plans Lab Setup For this lab, you will use the available virtual machine environment. Before you begin the lab, you must complete the following steps:

    1. On the host computer, click Start, point to Administrative Tools, and then click Hyper-V Manager. 2. Maximize the Hyper-V Manager window. 3. In the Virtual Machines list, if the virtual machine 623XB-MIA-DC is not started:

    Right-click 623XB-MIA-DC and click Start. Right-click 623XB-MIA-DC and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to log on message

    appears, and then close the Virtual Machine Connection window.4. In the Virtual Machines list, if the virtual machine 623XB-MIA-SQL is not started:

    Right-click 623XB-MIA-SQL and click Start. Right-click 623XB-MIA-SQL and click Connect. In the Virtual Machine Connection window, wait until the Press CTRL+ALT+DELETE to logon message

    appears. 5. In Virtual Machine Connection window, click on the Revert toolbar icon. 6. If you are prompted to confirm that you want to revert, click Revert. Wait for the revert action to complete. 7. In the Virtual Machine Connection window, if the user is not already logged on:

    On the Action menu, click the Ctrl-Alt-Delete menu item. Click Switch User, and then click Other User. Log on using the following credentials:

    i. User name: AdventureWorks\Administrator ii. Password: Pa$$w0rd

    8. From the View menu, in the Virtual Machine Connection window, click Full Screen Mode. 9. If the Server Manager window appears, check the Do not show me this console at logon check box and

    close the Server Manager window. 10. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2008 R2, and click SQL

    Server Management Studio.

    11. In Connect to Server window, type Proseware in the Server name text box.

    12. In the Authentication drop-down list box, select Windows Authentication and click Connect.

    13. In the File menu, click Open, and click Project/Solution.

    14. In the Open Project window, open the project D:\6232B_Labs\6232B_07_PRJ\6232B_07_PRJ.ssmssln.

    15. In Solution Explorer, double-click the query 00-Setup.sql. When the query window opens, click Execute on the toolbar.

    Exercise 1: Actual vs. Estimated Plans

    Task 1: Load the test script 1. In Solution Explorer, double-click the file

  • L7-2 Lab: Reading SQL Server Execution Plans

    51 Lab Exercise 1.sql. 2. Highlight the following section of the script:

    USE AdventureWorks2008R2; GO

    3. In the toolbar, click Execute.

    Task 2: Generate an estimated execution plan for script 7.1 1. Highlight the following section of the script

    SELECT * FROM dbo.DatabaseLog; GO

    2. From the Query menu, select Display Estimated Execution Plan.

    Note: A Table Scan operator was used.

    Task 3: View the estimated execution plan for script 7.2 using SHOWPLAN_XML 1. Highlight the following section of the script

    SET SHOWPLAN_XML ON; GO SELECT * FROM dbo.DatabaseLog; GO SET SHOWPLAN_XML OFF; GO

    2. In the toolbar, click Execute.

    3. In the Results pane, click on the XML that is returned to view the execution plan.

    4. In the Results pane, right-click in the whitespace in the plan, click Show Execution Plan XML.

    5. In the ExecutionPlanX.sqlplan tab, review the XML.

    Note: The XML is complex and it includes a large amount of detail that is not immediately obvious from the graphical plan.

    6. Close the XML window and the execution plan window. If prompted to save changes, do not save the changes.

    Task 4: Generate the actual execution plan for script 7.3 1. In the Query menu and click Include Actual Execution Plan.

    2. Highlight the following section of the script

    SELECT * FROM dbo.DatabaseLog; GO

    3. In the toolbar, click Execute.

  • Lab: Reading SQL Server Execution Plans L7-3

    4. Click on the Execution Plan pane.

    Note: The plan is identical to the estimated plan from the previous task.

    Task 5: Try to generate an estimated execution plan for script 7.4 1. Highlight the following section of the script

    CREATE TABLE dbo.SomeTable ( SomeTableID INT IDENTITY(1, 1) PRIMARY KEY, FullName varchar(35) ); INSERT INTO dbo.SomeTable VALUES('Hello'),('There'); SELECT * FROM dbo.SomeTable; DROP TABLE dbo.SomeTable; GO

    2. From the Query menu, select Display Estimated Execution Plan.

    Note: An Estimated Execution Plan cannot be created. Note the reason (invalid object name) for the inability to create a plan in the messages tab.

    Task 6: Review the actual execution plan for script 7.4 1. Highlight the following section of the script again

    CREATE TABLE dbo.SomeTable ( SomeTableID INT IDENTITY(1, 1) PRIMARY KEY, FullName varchar(35) ); INSERT INTO dbo.SomeTable VALUES('Hello'),('There'); SELECT * FROM dbo.SomeTable; DROP TABLE dbo.SomeTable; GO

    2. In the toolbar, click Execute.

    3. Review the Execution Plan that has been returned.

    Note: The returned plan shows the INSERT and SELECT statements but not the CREATE and DROP statements.

    Task 7: Review the execution plans currently cached in memory using script 7.5 1. Highlight the following section of the script

    SELECT cp.objtype AS PlanType, OBJECT_NAME(st.objectid,st.dbid) AS ObjectName, cp.refcounts AS ReferenceCounts, cp.usecounts AS UseCounts, st.text AS SQLBatch, qp.query_plan AS QueryPlan FROM sys.dm_exec_cached_plans AS cp CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) AS qp CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) AS st; GO

  • L7-4 Lab: Reading SQL Server Execution Plans

    2. In the toolbar, click Execute.

    3. Review the results being returned.

    Note: The results returned will vary from system to system. Browse through the rows in the Results tab to gain an understanding of the types of plans currently in memory.

    Exercise 2: Identify Common Plan Elements

    Task 1: Load the test script 1. In Solution Explorer, double-click the file

    61 Lab Exercise 2.sql. 2. Highlight the query as shown in the script below:

    USE AdventureWorks2008R2; GO

    3. In the toolbar, click Execute.

    4. From the Query menu click Include Actual Execution Plan.

    Task 2: Explain the actual execution plan from script 7.6 1. Highlight script 7.6 as shown in the code below

    SELECT * FROM Person.Person; GO

    2. In the toolbar, click Execute.

    3. Explain the results being returned.

    Note: The table has a clustered index and the entire table is being read.

    Task 3: Explain the actual execution plan from script 7.7 1. Highlight script 7.7 as shown in the code below

    SELECT * FROM Person.Person WHERE Person.BusinessEntityID = 12; GO

    2. In the toolbar, click Execute.

    3. Explain the results being returned.

    Note: The table has a clustered index and a specific clustering key is being used to seek.

    Task 4: Explain the actual execution plan from script 7.8 1. Highlight script 7.8 as shown in the code below

    SELECT * FROM Production.ProductInventory ORDER BY Shelf;

  • Lab: Reading SQL Server Execution Plans L7-5

    GO

    2. In the toolbar, click Execute.

    3. Explain the results being returned.

    Note: The table has a clustered index and the entire table is being read. The rows are then sorted by Shelf.

    Task 5: Explain the actual execution plan from script 7.9 1. Highlight script 7.9 as shown in the code below

    SELECT * FROM dbo.DatabaseLog WHERE DatabaseLogID = 1; GO

    2. In the toolbar, click Execute.

    3. Explain the results being returned.

    Note: The table is structured as a heap. The table has a nonclustered index on DatabaseLogID that is being used to locate the row required. Because the entire row is then required, a lookup is being made into the heap.

    Task 6: Explain the actual execution plan from script 7.10 1. Highlight script 7.10 as shown in the code below

    SELECT AddressID, AddressLine1, AddressLine2, City, StateProvinceID, PostalCode FROM Person.Address WHERE StateProvinceID = 32; GO

    2. In the toolbar, click Execute.

    3. Explain the results being returned.

    Note: The table has a clustered index. There is a nonclustered index that is sufficiently selective to be useful in locating entries for the given StateProvinceID. After the rows are located by that index, lookups to the clustered index need to be performed because not all columns that are required for the query are contained within the nonclustered index.

    Task 7: Explain the actual execution plan from script 7.11 1. Highlight script 7.11 as shown in the code below

    SELECT AddressID, AddressLine1, AddressLine2, City, StateProvinceID, PostalCode FROM Person.Address WHERE StateProvinceID = 79; GO

    2. In the toolbar, click Execute.

  • L7-6 Lab: Reading SQL Server Execution Plans

    3. Explain the results being returned. Compare this plan to the one returned in script 7.10.

    4. The reason why the plans are different can be attributed to

    Note: SQL Server has chosen to scan an entire index as it covers the query. The rows with the correct StateProvinceID are being selected from that index. Note the Missing Index hint that appears.

    Task 8: Explain the actual execution plan from script 7.12 1. Highlight script 7.12 as shown in the code below

    SELECT City, COUNT(City) AS CityCount FROM Person.Address GROUP BY City; GO

    2. In the toolbar, click Execute.

    3. Explain the results being returned.

    Note: SQL Server has decided to read an entire index that contains the City column rather than reading the entire table. As the index is not in City order, it then needs to execute a hash match aggregate operation to calculate the required aggregate.

    Task 9: Explain the actual execution plan from script 7.13 1. Highlight script 7.13 as shown in the code below

    SELECT StateProvinceID, COUNT(1) AS StateProvinceCount FROM Person.Address GROUP BY StateProvinceID; GO

    2. In the toolbar, click Execute.

    3. Explain the results being returned. Compare this plan to the one returned in script 7.12.

    4. The reason why the plans are different can be attributed to

    Note: There is a nonclustered index that is in StateProvinceID order. SQL Server has chosen to scan that index. As it is already in StateProvinceID order, a stream aggregate operation was able to be performed.

    Task 10: Explain the actual execution plan from script 7.14 1. Highlight script 7.14 as shown in the code below

    SELECT City, COUNT(City) AS CityCount FROM Person.Address GROUP BY City HAVING COUNT(1) > 5; GO

    2. In the toolbar, click Execute.

  • Lab: Reading SQL Server Execution Plans L7-7

    3. Note the difference in this plan from the plan for script 7.12.

    Note: This query is identical to the one in script 7.12 with the addition of the HAVING clause. That clause has caused SQL Server to add a filter operation.

    Challenge Exercise 3: Query Cost Comparison (Only if time permits)

    Task 1: Load the test script 1. In Solution Explorer, double-click the file

    71 Lab Exercise 3.sql. 2.