Beruflich Dokumente
Kultur Dokumente
2778A
Writing Queries Using Microsoft SQL Server
2008 Transact-SQL
Companion Content
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 and the trademarks listed at
http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks
of the Microsoft group of companies. All other marks are property of their respective owners.
Module 1
Getting Started with Databases and Transact-SQL in SQL
Server 2008
Contents:
Lesson 1: Overview of SQL Server 2008 2
Lesson 2: Overview of SQL Server Databases 5
Lesson 3: Overview and Syntax Elements of T-SQL 7
Lesson 4: Working with T-SQL Scripts 9
Lesson 5: Using T-SQL Querying Tools 11
Module Reviews and Takeaways 13
Lab Review Questions and Answers 15
1-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Overview of SQL Server 2008
Contents:
Question and Answers 3
Additional Reading 4
Getting Started with Databases and Transact-SQL in SQL Server 2008 1-3
Answer: Answers will vary, but will include multitier web applications and two-tier client line of
business applications.
1-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Overview of Client/Server Architecture
Chapter 7 - Client/Server Architecture
File-Server vs. Client/Server
Lesson 2
Overview of SQL Server Databases
Contents:
Additional Reading 6
1-6 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Overview of Relational Databases
Databases
Relational Database Components
Database Engine Concepts
Relational Databases
What is Normalization?
Normalization
SQL Database Normalization Rules
Lesson 3
Overview and Syntax Elements of T-SQL
Contents:
Additional Reading 8
1-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
A History and Definition of ANSI SQL and T-SQL
Using Common Table Expressions
Control-of-flow Statements
Control-of-Flow
Conditional Statement Syntax
GOTO (Transact-SQL)
Getting Started with Databases and Transact-SQL in SQL Server 2008 1-9
Lesson 4
Working with T-SQL Scripts
Contents:
Additional Reading 10
1-10 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
What are Batch Directives?
ELSE (IF...ELSE)
Lesson 5
Using T-SQL Querying Tools
Contents:
Additional Reading 12
1-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Tools for Querying SQL Server 2008 Databases
Query Tools
bcp Utility
sqlcmd Utility
Answer: An example of third tier client/server architecture would be a client that connects to a web
server that connects to SQL Server 2008 for access to the data.
Question: Which server management tool do we use to create optimal sets of indexes and partitions?
Answer: Database Engine Tuning Advisor helps create optimal sets of indexes, indexed views, and
partitions.
Question: How would you quickly create graphs and reports from SQL data?
Question: What are the two main parts of the relational database server?
Answer: The relational database server of SQL Server has two main parts: the relational engine and
the storage engine.
Formatting
o Capitalize reserve words.
o Code should be indented properly.
Naming Objects
o Objects should be placed in square brackets.
[Customers]
o Retain the case of the table names as in the database.
[OrderDetails]
o Include schema in object names.
Sales.Customers
Use ANSI SQL
Comment Code
1-14 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Tools
Tool Use for Where to find it
Microsoft SQL Server Managing SQL server Start | All Programs | Microsoft SQL Server 2008
Management Studio databases and tables.
SQL Server Business Managing SQL server Start | All Programs | Microsoft SQL Server 2008
Intelligence Development applications.
Studio
Getting Started with Databases and Transact-SQL in SQL Server 2008 1-15
Answer: SQLCMD can be launched from the command line, in a script or through an application,
allowing a SQL script to be launched programmatically or without the Management Studio.
Question: What are the four main tools for querying SQL Server 2008 databases?
Answer: SQL Server Management Studio, Microsoft Office Excel, and SQLCMD. PowerShell can also
query SQL Server 2008 databases, but we did not use it in the lab.
Question: How is Excel useful when querying SQL Server 2008 databases?
Answer: Excel can collect large amounts of data and perform visualization, reporting, and analysis on
the desktop.
Querying and Filtering Data 2-1
Module 2
Querying and Filtering Data
Contents:
Lesson 1: Using the SELECT Statement 2
Lesson 2: Filtering Data 6
Lesson 3: Working with NULL Values 10
Lesson 4: Formatting Result Sets 14
Lesson 5: Performance Considerations for Writing Queries 18
Module Reviews and Takeaways 20
Lab Review Questions and Answers 21
2-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Using the SELECT Statement
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Querying and Filtering Data 2-3
Answer:
Additional Reading
Elements of the SELECT Statement
Parts of a SELECT Statement
Query Fundamentals
Lesson 2
Using Variables
Contents:
Question and Answers 7
Detailed Demo Steps 8
Additional Reading 9
Querying and Filtering Data 2-7
Answer: LIKE is a very common comparison operator. This is generally because part of a string is
often known with other parts being variable. CONTAINS and FREETEXT are also good options for this
answer. = is typically not common for string comparisons since the data has a high potential of being
variable, particularly in longer string values. For short string values such as codes, = is more common.
Question: In the LIKE statement, where is the appropriate location to place the % sign and why?
Answer: After the first character. This will allow the SQL statement to run using and index for that
column, if one is available. When the % sign is at the beginning of the criteria string, all values in that
column must be compared with the criteria. Indexes are not used.
Answer: The NOT operator must first determine if the comparison is TRUE or FALSE and then
perform additional processing to change the result to the opposite one. On queries with large row
sets this can extra processing can affect performance.
2-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Retrieving Specific Rows in a Table
Predicate (Transact-SQL)
WHERE (Transact-SQL)
Search Condition (Transact-SQL)
Operator Precedence
Logical Operators (Transact-SQL)
Lesson 3
Working with NULL Values
Contents:
Question and Answers 11
Detailed Demo Steps 12
Additional Reading 13
Querying and Filtering Data 2-11
Answer:
Columns that commonly contain NULL values are those of data types: char, nchar, varchar,
nvarchar, text, ntext. Numeric columns may contain NULL data, but it is not advisable.
The easiest way to check column data types is to check in SQL Server Management Studio. If you
do not have access to this tool then requesting the information from IT is a good idea.
Answer:
ISNULL() queries with data that you want to check for NULL values.
NULLIF() queries that you want to offer a more meaningful value in place of the NULL keyword
being displayed in the result.
COALESCE() Queries where NULL values may exist and you wish to substitute one of several
possibilities into a column of the result set.
2-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Three useful functions for dealing with NULL values in column data.
1. Return to the VM, click NEW Query, and open file E:\MOD02\democode\NULLDemo.sql.
2. Highlight the code for the first demo and click Execute.
3. Explain that the first uses the ISNULL() function to examine the MaxQty column and returns the
value 0.00 if the MaxQty column value is NULL. Point out that the first result set does not use
ISNULL() and displays NULL as the column value. The second result set displays 0.00 in the rows
that previously showed a NULL value. You may need to scroll down to view the second result set.
4. Highlight the code for the second demo and click Execute.
5. In this result set point out that the NULLIF() function assigned a NULL value in the Null if Equal
column for those rows that have the same value in the MakeFlag and FinishedGoodsFlag
columns. It also shows the value of the MakeFlag column if the two columns do not have the
same value.
6. Highlight the code for the third example and click Execute. Note that the COALESCE() function
will look at the value of each argument listed and return the value of the first argument that does
not have a NULL value.
7. Note that the Total Salary column is populated with data based on the following criteria in the
COALESCE() function:
If the hourly_wage column has a value Total Salary has a calculated value based on the
hourly_wage * 40 hours * 52 weeks.
If the salary column is not NULL the value of the salary column is displayed in Total Salary.
If the commission column is not NULL the value displayed in Total Salary is equal to commission *
num_sales.
8. Keep the VM running and SQL Management Studio open.
Querying and Filtering Data 2-13
Additional Reading
Considerations for Working with NULL Values
Null Values
Using Sparse Columns
Lesson 4
Formatting Result Sets
Contents:
Question and Answers 15
Detailed Demo Steps 16
Additional Reading 17
Querying and Filtering Data 2-15
Answer: Because DISTINCT only looks at the result set it will only evaluate the rows and columns that
are present. If any of the data would be considered duplicate based on columns that are not in the
select list, these columns will not be taken into consideration.
Using Expressions
Question: The above examples show how expressions can be used. What other ways do think you will
use expressions to create queries?
Answer: They can be used as possible values in comparisons, static values in derived columns, static
values in concatenated columns.
Answer:
Hide or display data based on user information for security reasons.
Hide or display data based on parameter values.
2-16 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Sorting Data
ORDER BY Clause (Transact-SQL)
Sorting Rows with ORDER BY
Using Expressions
+ (String Concatenation) (Transact-SQL)
Functions (Transact-SQL)
Derived Column Transformation
2-18 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 5
Performance Considerations for Writing Queries
Contents:
Additional Reading 19
Querying and Filtering Data 2-19
Additional Reading
How SQL Server Processes Transact-SQL Queries
SQL Statement Processing
Query Performance
Query Tuning Recommendations
Answer: Placement of wildcards after the first character will allow the use of indexes.
Avoid using the asterisk in the SELECT list.
Avoid using NOT in conditions when possible.
Use constants instead of expressions or calculations for comparisons.
Question: NULL values are present in many databases, usually by design. What can you do to
discover where NULL values may be stored? Why is it important to know where NULL values can be
encountered?
Answer: The easiest method is to examine the table schema in SQL Server Management Studio and
note the columns that allow NULL values. Alternatively, you can obtain the schema from IT.
Answer: The cause is most likely that the columns allow NULL values and have not been populated.
To solve the issue the COALESCE() and ISNULL() functions can be used to replace NULL values in the
query output.
Question: You are asked to quickly create a report on a table with a large number of data rows in it.
When writing the query, what are some things you can do to help the system retrieve the required
rows as quickly as possible?
Answer:
Answer: Using an asterisk returns all columns in the row. Some of the columns may contain large
amounts of data, or even unreadable data, thus cluttering the output. Performance of the query can
also be adversely affected if some of the columns contain large binary data. Instead of using the * you
should list specific column names in the SELECT list.
Question: When a column in your query can contain NULL values you may get unexpected results in
the data set. What are some of the techniques that can be used to ensure that all of the expected
data is listed?
Answer:
NULL values are considered undefined values. This means that any attempt to directly use
columns with NULL values will not return expected results.
o Calculations will return undefined values.
o Rows of data may not be in the data set.
o Concatenated columns will be returned as blank in the data set.
The following functions can be used to accommodate NULL values:
o ISNULL() will replace a NULL value with a given value in the data set.
o COALESCE() allows you to designate a number of values that can be substituted for NULL
values. Each column or value listed is tested for a NULL value and the first one to not have a
NULL value is used in the data set.
o IS NULL is used to test for NULL values in a column in the WHERE clause.
Question: When performing string comparisons on a column you can use LIKE, CONTAINS, and
FREETEXT. What are the differences and when would each be best used?
Answer:
LIKE uses wildcards to search for partial matches in text columns. LIKE is best used when the
strings are relatively short and spelling is the main consideration for the search.
CONTAINS uses a word or list of words to search strings in a column. CONTAINS is best used
for larger columns and when derivatives of the word are also desired such as drive, drove,
driving, and driven.
FREETEXT uses a word or list of words on large text data that has been indexed using Full Text
indexing. FREETEXT also allows you to search for derivatives of the word or words in the list.
Grouping and Summarizing Data 3-1
Module 3
Grouping and Summarizing Data
Contents:
Lesson 1: Summarizing Data by Using Aggregate Functions 2
Lesson 2: Summarizing Grouped Data 6
Lesson 3: Ranking Grouped Data 10
Lesson 4: Creating Crosstab Queries 13
Module Reviews and Takeaways 15
Lab Review Questions and Answers 16
3-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Summarizing Data by Using Aggregate Functions
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Grouping and Summarizing Data 3-3
Answer: Since most of the aggregate functions ignore NULL values when performing their
calculations, it can introduce errors into your output if the NULL values are handled incorrectly. When
using SUM, the NULL values will be treated as zero and thus should be ok. But if you are using the
AVG or COUNT functions your results will not be correct. Use the featured ISNULL example to
correctly handle these cases.
Answer: The custom aggregate will execute faster as it is compiled code (T-SQL is interpreted) and
may also simplify queries by making them easier to read and understand, thus easing query
maintenance.
Question: How can you restrict one of the sample queries in this demo to only account for a certain
range of employees?
Create a new query in SQL Server Management Studio. Make sure the current database is set to
AdventureWorks2008
Enter and then run the following query to produce a count of the employees in the system:
o SELECT COUNT(*) FROM HumanResources.Employee;
Enter and then run the following query to calculate the average number of vacation hours each
employee has:
o SELECT AVG(VacationHours) FROM HumanResources.Employee;
Enter and then run the following query to calculate the maximum number of vacation hours held
by an employee:
o SELECT MAX(VacationHours) FROM HumanResources.Employee;
Enter and then run the following query to calculate the total number of vacation hours held by
employees:
o SELECT SUM(VacationHours) FROM HumanResources.Employee;
Grouping and Summarizing Data 3-5
Additional Reading
Using Aggregate Functions Native to SQL Server
Summarizing Data
Deterministic and Nondeterministic Functions
Aggregate Functions
Lesson 2
Summarizing Grouped Data
Contents:
Question and Answers 7
Detailed Demo Steps 8
Additional Reading 9
Grouping and Summarizing Data 3-7
Answer: Grouping data, and by extension the GROUP BY clause, is one of the most fundamental
concepts in Transact SQL. It is through this clause that the query processor knows how to process
your aggregation functions on groups of data and not an entire table. Without GROUP BY it would
be impossible to generate summary information on any level other than that of a table level.
Answer: The HAVING and WHERE clauses are similar but not the same. HAVING behaves like a
WHERE but applies to groups as a whole whereas the WHERE clause applies to individual rows. It is
only when a GROUP BY is not used that HAVING is behaves like a WHERE clause. In this case, since
performance will be identical, you should probably use the language construct that makes it the most
clear what you are doing.
Answer: A quick factor may be the handling of NULL values as each operator handles them a bit
differently.
Answer: There can be several advantages. One clear advantage is summary information at different
levels can be returned in a single call instead of multiple calls.
3-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Create a new query in SQL Server Management Studio. Make sure the current database is set to
AdventureWorks2008
Enter and then run the following ROLLUP query:
o USE AdventureWorksDW2008;
GO
SELECT ProductKey, OrderDateKey, DueDateKey, ShipDateKey, SUM (SalesAmount) AS
[Sales]
FROM dbo.FactInternetSales
GROUP BY ROLLUP(ProductKey, OrderDateKey, DueDateKey, ShipDateKey);
Enter and then run the following CUBE query:
o USE AdventureWorksDW2008;
GO
SELECT ProductKey, OrderDateKey, DueDateKey, ShipDateKey,SUM (SalesAmount) AS
[Sales]
FROM dbo.FactInternetSales
GROUP BY CUBE(ProductKey, OrderDateKey, DueDateKey, ShipDateKey);
Grouping and Summarizing Data 3-9
Additional Reading
Using the GROUP BY Clause
GROUP BY (Transact-SQL)
Lesson 3
Ranking Grouped Data
Contents:
Question and Answers 11
Additional Reading 12
Grouping and Summarizing Data 3-11
Answer: DENSE_RANK.
3-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
What is Ranking?
Ranking Functions (Transact-SQL)
Over Clause (Transact-SQL)
Lesson 4
Creating Crosstab Queries
Contents:
Additional Reading 14
3-14 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
How the PIVOT and UNPIVOT Operators Work
Using PIVOT and UNPIVOT
Question: The HAVING clause is very similar to the WHERE clause with one notable difference. What
is the difference?
Answer: HAVING filters after the SELECT but before the results are returned. WHERE filters in the
SELECT.
Question: Which ranking function would be appropriate for a sports league rankings query?
Answer: RANK, because ties are present, with gaps between tied ranks.
Question: Creating cross tab queries is probably one of the most common uses for what operator?
Answer: The server returns this warning as a convenience, letting you know that null values were not
respected by your operation. This could potentially save you some debugging time later if you were
not expecting the null value elimination. Other exercises in the lab show you how to explicitly
eliminate null values from your queries.
Question: When executing your query you receive the error Column xyz is invalid in the select list
because it is not contained in either an aggregate function or the GROUP BY clause. What did you
forget to do?
Answer: This error occurs most frequently when you forget to include columns in the select list that
arent used with aggregates into the GROUP BY clause.
Question: When ranking the salespersons into four categories based on their year to date sales, were
the amount of results in each category even? Why or why not?
Answer: If the number of rows in a category is not divisible by number of categories, the size of the
groups will differ by one member. Additionally, the larger group will come before the others.
Joining Data from Multiple Tables 4-1
Module 4
Joining Data from Multiple Tables
Contents:
Lesson 1: Querying Multiple Tables by Using Joins 2
Lesson 2: Applying Joins for Typical Reporting Needs 6
Lesson 3: Combining and Limiting Result Sets 10
Module Reviews and Takeaways 14
Lab Review Questions and Answers 16
4-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Querying Multiple Tables by Using Joins
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Joining Data from Multiple Tables 4-3
Answer: When you need to return all rows from at least one of the tables or views mentioned in the
FROM clause instead of eliminating rows as an inner join would do.
Question: Can you think of any scenarios in which you would use a cross join?
Answer: If you want to run a query that will return data for every month, for example, even on
customers that had no orders that particular month, you could use a Cartesian product to get that
data.
4-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Fundamentals of Joins
PRIMARY KEY Constraints
FOREIGN KEY Constraints
Lesson 2
Applying Joins for Typical Reporting Needs
Contents:
Question and Answers 7
Detailed Demo Steps 8
Additional Reading 9
Joining Data from Multiple Tables 4-7
Answer: A translation (or intermediate) table is the middle table in a join when you are joining three
or more tables.
Answer: As a general rule, not-equal joins make sense only when used with a self-join.
4-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Joining Tables in a User-Defined Function
Views
4-10 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 3
Combining and Limiting Result Sets
Contents:
Question and Answers 11
Detailed Demo Steps 12
Additional Reading 13
Joining Data from Multiple Tables 4-11
Answer: Sometimes you want to determine how many rows are returned by a query, for example in a
table that contains dates you may only want to return some number or percentage of the most
recent rows added or modified. You can use the TOP clause to do this.
Answer: Whenever you need a truly random sample of data from your database, such as in some
data mining applications where you need a sampling mechanism, you can use TABLESAMPLE. With
TABLESAMPLE you are able to get a sample set of data without having to sift through the database
manually.
Answer: The following are basic rules for combining the result sets of two queries by using UNION:
The number and the order of the columns must be the same in all queries.
The data types must be compatible.
Question: How do you think rows are returned from a SELECT TOP statement that also has an ORDER
BY clause?
Answer: If a SELECT statement that includes TOP also has an ORDER BY clause, the rows to be
returned are selected from the ordered result set. The whole result set is built in the specified order
and the top n rows in the ordered result set are returned.
Question: What conditions must be met in order to use TABLESAMPLE to return a sample from a
large table?
Answer: You can use TABLESAMPLE to quickly return a sample from a large table when either of the
following conditions is true:
The sample does not have to be a truly random sample at the level of individual rows.
Rows on individual pages of the table are not correlated with other rows on the same page.
4-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Limiting Result Sets by Using the EXCEPT and INTERSECT Operators
Collation Precedence (Transact-SQL)
4-14 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Answer: By specifying the column from each table to be used for the join or by specifying a logical
operator (for example, = or <>,) to be used in comparing values from the columns.
Question: How can multiple join operators be combined in the same statement?
Answer: The join expressions can be connected using the AND or OR operators.
Question: What options are available to the TABLESAMPLE clause and what are they used for?
Answer: SYSTEM and REPEATABLE. SYSTEM returns an approximate percentage of rows and
generates a random value for each physical 8-KB page in the table. REPEATABLE causes a selected
sample to be returned again.
Answer: All the columns in both tables, and returns only the rows for which there is an equal value in
the join column.
Question: What results did the Left Outer Join and Right Outer Join in Exercise 1 return?
Answer: The Left Outer Join included all rows in the Product table in the results, whether or not there
was a match on the ProductID column in the ProductReview table. The Right Outer Join returned all
sales persons in the results, regardless of whether they are assigned a territory.
Question: Why was the ProductVendor table given two different table aliases in the FROM clause of
Exercise 2?
Answer: Because the ProductVendor table appears in two roles and those aliases were used to qualify
the column names in the rest of the query.
Question: What would happen if we added an ORDER BY clause to the TOP select statement in
Exercise 3?
Answer: The rows to be returned would be selected from the ordered result set instead of from the
standard, unordered result set.
Working with Subqueries 5-1
Module 5
Working with Subqueries
Contents:
Lesson 1: Writing Basic Subqueries 2
Lesson 2: Writing Correlated Subqueries 6
Lesson 3: Comparing Subqueries with Joins and Temporary Tables 9
Lesson 4: Using Common Table Expressions 11
Module Reviews and Takeaways 15
Lab Review Questions and Answers 16
5-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Writing Basic Subqueries
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Working with Subqueries 5-3
Answer:
Question: What results were returned by the SELECT statement that contained an ANY expression
and why?
Answer: The products whose list prices are greater than or equal to the maximum list price of any
product subcategory.
5-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
What are Subqueries?
ALL (Transact-SQL)
SOME | ANY (Transact-SQL)
Lesson 2
Writing Correlated Subqueries
Contents:
Question and Answers 7
Detailed Demo Steps 8
Working with Subqueries 5-7
Answer:
1. Outer query passes column values to the inner query.
Answer: Sales where the quantity is less than the average quantity for sales of that product.
5-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 3
Comparing Subqueries with Joins and Temporary
Tables
Contents:
Additional Reading 10
5-10 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Temporary Tables
table (Transact-SQL)
Working with Subqueries 5-11
Lesson 4
Using Common Table Expressions
Contents:
Question and Answers 12
Detailed Demo Steps 13
Additional Reading 14
5-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Answer: When the statement was executed, the CTE was referenced two times: one time to return
the selected columns for the salesperson, and again to retrieve similar details for the salesperson's
manager. The data for both the salesperson and the manager were returned in a single row.
Question: What would happen if you created a recursive CTE that returned the same values for both
the parent and child columns?
Answer: You would create an infinite loop. Note that, when testing the results of a recursive query,
you can limit the number of recursion levels allowed for a specific statement by using the
MAXRECURSION hint and a value between 0 and 32,767 in the OPTION clause of the INSERT,
UPDATE, DELETE, or SELECT statement.
Working with Subqueries 5-13
Additional Reading
Writing Recursive Queries by Using Common Table Expressions
Recursive Queries Using Common Table Expressions
Working with Subqueries 5-15
Answer: A regular SELECT query including the regular select list components, a regular FROM clause
including one or more table or view names, an optional WHERE clause, an optional GROUP BY clause,
and an optional HAVING clause.
Question: What clauses can the SELECT query of a subquery include? What clauses can it not
include?
Answer: The SELECT query of a subquery cannot include a COMPUTE or FOR BROWSE clause, and
may only include an ORDER BY clause when a TOP clause is also specified.
Answer: Those that operate on lists introduced with IN, or those that a comparison operator
modified by ANY or ALL; those that are introduced with an unmodified comparison operator and
must return a single value; those that are existence tests introduced with EXISTS..
Answer: By executing the subquery once and substituting the resulting value or values into the
WHERE clause of the outer query.
Answer: These subqueries depends on the query for their values. This means that the subquery is
executed repeatedly, once for each row that might be selected in the outer query.
Answer: Creating a recursive query, substituting for a view when the general use of a view is not
required, enabled grouping by a column that is derived from a scalar subselect, or referencing the
resulting table multiple times in the same statement.
Modifying Data in Tables 6-1
Module 6
Modifying Data in Tables
Contents:
Lesson 1: Inserting Data into Tables 2
Lesson 2: Deleting Data from Tables 6
Lesson 3: Update Data in Tables 10
Lesson 4: Overview of Transactions 14
Module Reviews and Takeaways 18
Lab Review Questions and Answers 20
6-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Inserting Data into Tables
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Modifying Data in Tables 6-3
Answer: Because you have to insert an explicit value in the IDENTITY column for SQL Server to
increment.
Question: Under what circumstances must the column_list portion of the INSERT statement be
defined?
Answer: column_list and VALUES list must be used when explicit values are inserted into an identity
column, and the SET IDENTITY_INSERT option must be ON for the table.
6-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
INSERT Fundamentals
INSERT (Transact SQL)
Lesson 2
Deleting Data from Tables
Contents:
Question and Answers 7
Detailed Demo Steps 8
Additional Reading 9
Modifying Data in Tables 6-7
Answer: The TRUNCATE TABLE statement is a fast, efficient method of deleting all rows in a table.
Answer: Both the DELETE and TRUNCATE statements delete only rows from the table; the table must
be removed from the database by using the DROP TABLE statement.
6-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Delete Fundamentals
DELETE (Transact-SQL)
Lesson 3
Update Data in Tables
Contents:
Question and Answers 11
Detailed Demo Steps 12
Additional Reading 13
Modifying Data in Tables 6-11
Answer: SET, FROM, and WHERE. Definitions of these clauses are available on slide 19 of this slide
deck.
Question: How would you write an UPDATE statement to increase the price of all products on a table
by 10 percent?
Answer: You would use the TOP clause with a (10) PERCENT argument, such as in the following:
UPDATE TOP (10) PERCENT Production.Product SET ListPrice = ListPrice * 1.1
6-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
UPDATE Fundamentals
UPDATE (Transact-SQL)
Changing Data by Using UPDATE
Lesson 4
Overview of Transactions
Contents:
Question and Answers 15
Detailed Demo Steps 16
Additional Reading 17
Modifying Data in Tables 6-15
Answer: If errors are encountered, all data modifications made after the BEGIN TRANSACTION can
be rolled back using the ROLLBACK TRANSACTION statement to return the data to this known state
of consistency. Each transaction lasts until either it completes without errors and COMMIT
TRANSACTION is issued to make the modifications a permanent part of the database, or errors are
encountered and all modifications are erased with a ROLLBACK TRANSACTION statement.
Answer: For each Transact-SQL statement that follows, SQL Server holds all of the shared locks until
the end of the transaction.
Answer: This indicates that the commit of the inner transaction from the transaction OutOfProc was
overridden by the subsequent rollback.
6-16 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Transaction Fundamentals
Transactions (Database Engine)
Distributed Transactions (Database Engine)
Question: How can the INSERT and SELECT statements be used to add rows to a table?
Answer: Use the INSERT statement to specify values directly or from a subquery, use the SELECT
statement with the INTO clause.
Question: What happens when a WHERE clause is not specified in a DELETE statement?
Answer: If a WHERE clause is not specified, all the rows in table_or_view are deleted.
rows violates a constraint, the statement is canceled, an error is returned, and no rows are
removed.
If you want to delete all the rows in a table, use the DELETE statement without specifying a
WHERE clause, or use TRUNCATE TABLE.
TRUNCATE TABLE is faster than DELETE and uses fewer system and transaction log resources.
Note: if you do use the TRUNCATE statement on a table, you will reset the identity seed
of any IDENTITY column in that table.
Answer: Because if all values for column names are listed in the same order as columns on the table,
we do not need to specify a column name list.
Question: How can we verify that a table has been deleted after using the DELETE statement?
Question: How can we write an UPDATE statement to ensure that all rows of a table are affected?
Answer: By omitting a WHERE clause that would specify the row or rows to update.
Querying Metadata, XML, and Full-Text Indexes 7-1
Module 7
Querying Metadata, XML, and Full-Text Indexes
Contents:
Lesson 1: Querying Metadata 2
Lesson 2: Overview of XML 6
Lesson 3: Querying XML Data 8
Lesson 4: Overview of Full-Text Indexes 13
Lesson 5: Querying Full-Text Indexes 15
Module Reviews and Takeaways 19
Lab Review Questions and Answers 20
7-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Querying Metadata
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Querying Metadata, XML, and Full-Text Indexes 7-3
Answer: The INFORMATION_SCHEMA is based on the ISO standard for metadata so metadata
queries using it will be portable between ISO standard databases.
Question: Why would you choose to use the System Stored Procedures and Functions to query
metadata?
Answer: System Stored Procedures and Functions provide a layer of abstraction that reduces the
need to understand the underlying system catalog
7-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
SELECT *
FROM sys.tables;
SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = N'Product';
Additional Reading
What Is Metadata?
Managing Metadata in SQL Server
Compatibility Views
Compatibility Views (Transact-SQL)
Lesson 2
Overview of XML
Contents:
Additional Reading 7
Querying Metadata, XML, and Full-Text Indexes 7-7
Additional Reading
What Is XML?
Understanding XML in SQL Server
Lesson 3
Querying XML Data
Contents:
Question and Answers 9
Detailed Demo Steps 10
Additional Reading 12
Querying Metadata, XML, and Full-Text Indexes 7-9
Answer: XQuery can be used in a query when data must be returned from a query that is contained
in an XML column and not the XML itself.
Answer: If XML is provided and the data contained in the XML is needed in relational format then
OpenXML can be used to shred the XML.
7-10 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
SELECT Cust.CustomerID,
OrderHeader.CustomerID,
OrderHeader.SalesOrderID,
OrderHeader.Status,
Cust.AccountNumber
FROM Sales.Customer Cust, Sales.SalesOrderHeader OrderHeader
WHERE Cust.CustomerID = OrderHeader.CustomerID
ORDER BY Cust.CustomerID
FOR XML AUTO
SELECT JobCandidateID,
Resume.value('declare namespace ns=
"http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume";
concat((/ns:Resume/ns:Name/ns:Name.First)[1], " ",
(/ns:Resume/ns:Name/ns:Name.Last)[1])',
'nvarchar(60)') AS FullName,
Resume.query('declare namespace ns=
"http://schemas.microsoft.com/sqlserver/2004/07/adventure-works/Resume";
for $ed in /ns:Resume/ns:Education
where $ed/ns:Edu.Level="Bachelor" and $ed/ns:Edu.Major="Business"
Querying Metadata, XML, and Full-Text Indexes 7-11
Additional Reading
Using For XML to Generate XML
FOR XML Support for String Data Types
Shredding XML
Using OPENXML
Lesson 4
Overview of Full-Text Indexes
Contents:
Additional Reading 14
7-14 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
What Are Full-Text Indexes?
SQL Server 2008 Full-Text Search Internals and Enhancements
Lesson 5
Querying Full-Text Indexes
Contents:
Question and Answers 16
Detailed Demo Steps 17
Additional Reading 18
7-16 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Answer: The full text search functions provide a ranking value for each query result which can be
useful in many situations.
Question: Why would you choose to use a full text search predicate rather than a function?
Answer: Full text search predicates are easy to use in existing queries and new queries without
adding the complexity of joining to the results of the function.
Querying Metadata, XML, and Full-Text Indexes 7-17
SELECT Name
FROM Production.Product
WHERE CONTAINS(Name, ' "Chain*" ');
Additional Reading
Overview of Full-Text Search
SQL Server 2008 Full-Text Search Internals and Enhancements
Full-Text Functions
Full-Text Search Query Fundamentals
Answer:FLWOR is the acronym for for, let, where, order by, and return which are the statements that
make up the FLWOR structure.
Question: What query language is specifically designed for querying data stored in XML?
Answer:XQuery is a query language designed and developed for querying data stored in XML.
Question: What is the difference between a full-text query predicate and function?
Answer:The difference is that the predicates return boolean (true/false) values so they are only useful
within WHERE clauses of queries. On the other hand, the functions return matches in table form.
7-20 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Answer: Metadata can be used for many requirements such as retrieving column names for tables,
determining the data type and other properties of columns, or monitoring database activity.
Answer: Compatibility views are provided to support applications that were developed on previous
versions of SQL Server and used deprecated metadata structures.
Answer: The FOR XML statement can be used to convert relational data to XML.
Question: What is the difference between the FREETEXT and CONTAINS predicates?
Answer: The FREETEXT predicate is a simplistic method for searching for words or forms of a word.
CONTAINS provides more advanced searching options such as finding words or phrases that are near
other words or phrases.
Using Programming Objects for Data Retrieval 8-1
Module 8
Using Programming Objects for Data Retrieval
Contents:
Lesson 1: Encapsulating Queries by Using Views 2
Lesson 2: Encapsulating Expressions by Using User-Defined Functions 6
Lesson 3: Overview of Stored Procedures and Triggers 10
Lesson 4: Overview of Triggers 14
Lesson 5: Writing Distributed Queries 18
Module Reviews and Takeaways 20
Lab Review Questions and Answers 21
8-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Encapsulating Queries by Using Views
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Using Programming Objects for Data Retrieval 8-3
Answer: Indexing a view improves the performance of views that have large result sets or are called
frequently.
Answer: Partitioning large tables into smaller tables improves performance and allows the load to be
distributed among database resources. Partitioned views allow these partitioned tables to be
combined into a single view to be queried.
8-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Create a view
Open a new query window and enter the following query:
Query a view
Open a new query window and enter the following query:
Additional Reading
What Are Views?
SQL Views
Indexed Views
Creating Indexed Views
Partitioned Views
Using Partitioned Views
Lesson 2
Encapsulating Expressions by Using User-Defined
Functions
Contents:
Question and Answers 7
Detailed Demo Steps 8
Additional Reading 9
Using Programming Objects for Data Retrieval 8-7
Answer: Scalar type user-defined functions return a single value and can be embedded into a query
to alter the value of a column.
Answer: Table type user-defined functions return multiple values in a row/column table structure and
can be queried like a table.
8-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
SELECT dbo.fnSquared(2)
SELECT dbo.fnSquared(8)
Additional Reading
What Are User-Defined Functions
User-defined Function Basics
Lesson 3
Overview of Stored Procedures
Contents:
Question and Answers 11
Detailed Demo Steps 12
Additional Reading 13
Using Programming Objects for Data Retrieval 8-11
Answer: Stored Procedures encapsulate common functionality so that it can be accessed from
whereever it is required.
8-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
What Are Stored Procedures?
CREATE PROCEDURE (Transact-SQL)
Lesson 4
Overview of Triggers
Contents:
Question and Answers 15
Detailed Demo Steps 16
Additional Reading 17
Using Programming Objects for Data Retrieval 8-15
Answer: An INSTEAD OF trigger executes before the insert, update, or delete occurs so it can be used
to validate the action before it happens and cancel it if necessary.
Question: Why would you use an AFTER trigger rather than an INSTEAD OF trigger?
Answer: An AFTER trigger executes after the insert, update, or delete occurs so it can be used to
perform subsequent action after the data has been changed.
8-16 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Create a trigger
Open a new query window and enter the following query:
Additional Reading
What Are Triggers?
CREATE TRIGGER (Transact-SQL)
Lesson 5
Writing Distributed Queries
Contents:
Additional Reading 19
Using Programming Objects for Data Retrieval 8-19
Additional Reading
How SQL Server? Works With Heterogeneous Data
Distributed Queries
Answer: Using the WITH ENCRYPTION option of CREATE PROCEDURE obfuscates the procedure
source.
Question: What special kind of stored procedure can be used to roll back an attempted data
modification in a SQL Server table?
Answer: A trigger is a stored procedure that is executed when a data modification is attempted.
Question: What types of data sources can be linked to SQL Server 2008 for distributed queries?
Answer: A scalar type user-defined function returns a single scalar value. A table type user-defined
function returns multiple values organized in a table structure.
Question: Why would a linked server be used instead of an ad hoc distributed query?
Answer: A linked server maintains a connection with the remote data source at the server level so
that all queries to that data source can share it. This allows changes in the connectivity as well as
security measures for it to be managed in a single location.
Answer: Since table type user-defined functions return multiple values in a table structure, they are
usually called within the FROM clause of a T-SQL query.
Question: Where are stored procedure execution plans stored after initial execution?
Answer: Compiled execution plans are stored in the stored procedure cache for future use.
Using Advanced Querying Techniques 9-1
Module 9
Using Advanced Querying Techniques
Contents:
Lesson 1: Considerations for Querying Data 2
Lesson 2: Working with Data Types 6
Lesson 3: Cursors and Set-Based Queries 10
Lesson 4: Dynamic SQL 14
Lesson 5: Maintaining Query Files 18
Module Reviews and Takeaways 20
Lab Review Questions and Answers 22
9-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 1
Considerations for Querying Data
Contents:
Question and Answers 3
Detailed Demo Steps 4
Additional Reading 5
Using Advanced Querying Techniques 9-3
Answer: Viewing the Estimated Execution Plan may reveal resource intensive operations before the
query is run.
Answer: Answers will vary, but some examples are: adding numbers to character strings, changing to
the money data type, or changing strings into date/time data.
Implicit Conversion
Question: When would you want to avoid implicit conversions?
Answer: Any time that you need to insure that an operation returns a specific data type, you should
avoid implicit conversions.
Answer: In SQL Server Management Studio, you can right-click Include Actual Execution Plan before
the query is run. You can also use a SET SHOWPLAN command in a query, or use SQL Server Profiler
to capture Showplan Events.
Answer: Because of data type precedence rules, some queries will succeed even though the data type
precedence rules will result in one data type being converted to another data type in a way that you
did not intend.
9-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Viewing estimated and actual execution plans with SQL Server Profiler
Start SQL Server Profiler and create a new trace.
In the Events tab, under Performance, select some of the different Showplan events and start
the trace.
In SQL Server Management Studio, execute the query again and review the execution plan in SQL
Server Profiler.
Additional Reading
Execution Plans
Execution Plans
Implicit Conversion
Data Type Conversions
Implicit Conversions
Lesson 2
Working with Data Types
Contents:
Question and Answers 7
Detailed Demo Steps 8
Additional Reading 9
Using Advanced Querying Techniques 9-7
Answer: The insert will succeed, but SQL Server will supply default values for the missing portion.
Answer: GetDescendant queries the next level down in the hierarchy, while GetAncestor queries the
next level up in the hierarchy.
9-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Recommendations for Querying Date/Time Data
Using Time and Date Data
Date and Time Data Types and Functions
Lesson 3
Cursors and Set-Based Queries
Contents:
Question and Answers 11
Detailed Demo Steps 12
Additional Reading 13
Using Advanced Querying Techniques 9-11
Answer: Frequently, cursors are used to keep a running tally of a changing numeric value.
Answer: In most cases, set-based queries run more quickly and are less resource-intensive than
cursors.
9-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Use a cursor
Open E:\MOD09\Democode\CursorSample.sql.
Review and execute the query. The code produces a list of products from the
AdventureWorks2008 database.
Additional Reading
Understanding Cursors
Cursors (Database Engine)
Cursor Implementations
Cursor Implementations
Using Cursors
Cursors (Database Engine)
DECLARE CURSOR:
Using DEALLOCATE
Query Fundamentals
9-14 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Lesson 4
Dynamic SQL
Contents:
Question and Answers 15
Detailed Demo Steps 16
Additional Reading 17
Using Advanced Querying Techniques 9-15
Answer: sp_executesql is more likely to produce a reusable execution plan, so EXECUTE is normally
used for simple situations where plan reusability is not a consideration.
Answer: SQL injection, if successful, can allow an unauthorized user to access, modify, or destroy data
very easily. All input must be validated when building dynamic SQL strings to help avoid SQL
injection.
Answer: Variables are used to store the individual strings of information that are then joined
together to form the query.
9-16 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Additional Reading
Introducing Dynamic SQL
Dynamic SQL
Lesson 5
Maintaining Query Files
Contents:
Additional Reading 19
Using Advanced Querying Techniques 9-19
Additional Reading
What are Versioning and Source Control?
Source Control Basics
Answer: Cursors handle the result sets on a row-by-row basis. Each row is fetched into the cursor,
where any read or update operations are performed, and then then next row is fetched into the
cursor.
Question: What functions are used to perform explicit data type conversions?
Answer: CAST and CONVERT are used to perform explicit data type conversions. CAST is the more
portable of the two functions, while CONVERT provides additional style options for date and time
conversions.
Answer: Dynamic SQL queries can be executed with sp_executesql or EXECUTE. Sp_executesql is
more likely to produce reusable execution plans and is usually the recommended method for
executing dynamic SQL statements.
Cannot implicitly or explicitly convert string or Conversion to the xml data type will fail if the XML
number data to xml data type is not well-formed.
Implicit conversions to binary data type If the binary data type is too small for the
produces unexpected results conversion, the leading digits are silently truncated.
Conversion will succeed, but the results will be
wrong.
Converting integers to character data types If the integer is too big for the character
implicitly results in an asterisk (*) instead of the conversion, an asterisk is used in implicit
correct value. conversions.
Test the size and data type of input and enforce appropriate limits. This can help prevent
deliberate buffer overruns.
Never build Transact-SQL statements directly from user input.
Answer: The data to be converted must result in well-formed XML, or the conversion will fail.
Answer: Use the GetRoot() function to determine the root level and use the result as the basis for an
INSERT statement to create the root node.
Question: When using a cursor, how do you retrieve the next row in the result set?
Resources
Contents:
Microsoft Learning 2
TechNet and MSDN Content 3
Knowledgebase 9
Communities 10
Books 11
R-2 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Microsoft Learning
This section describes various Microsoft Learning programs and offerings.
Microsoft Skills Assessments
Describes the skills assessment options available through Microsoft.
Microsoft Learning
Module 1
Chapter 7 - Client/Server Architecture
File-Server vs. Client/Server
Editions and Components of SQL Server 2008
Installing SQL Server 2005
Relational Databases
Normalization
SQL Database Normalization Rules
Identifiers
Using Extended Properties on Database Objects
Deprecated Database Engine Features in SQL Server 2008
Data Types (Transact-SQL)
Using Common Table Expressions
GRANT (Transact-SQL)
Query Fundamentals
Transact-SQL Syntax Conventions (Transact-SQL)
Transact-SQL Reference (Transact-SQL)
Functions (Transact-SQL)
Transact-SQL Variables
Expressions (Transact-SQL)
Control-of-Flow
Conditional Statement Syntax
GOTO (Transact-SQL)
ELSE (IF...ELSE)
TRY...CATCH (Transact-SQL)
RAISERROR (Transact-SQL)
R-4 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
bcp Utility
sqlcmd Utility
Query Tools
Features in SQL Server Management Studio
Developing Solutions and Projects in SQL Server Management Studio
Introduction to Solutions, Projects, and Items
Module 2
+ (String Concatenation) (Transact-SQL)
Analyzing a Query
Assigning Result Set Column Names
BETWEEN (Transact-SQL)
Checklist for Analyzing Slow-Running Queries
COALESCE (Transact-SQL)
Comparison Operators
Comparison Operators (Transact-SQL)
CONTAINS (Transact-SQL)
Derived Column Transformation
Eliminating Duplicates with DISTINCT
Expressions (Transact-SQL)
FREETEXT (Transact-SQL)
Functions (Transact-SQL)
IN (Transact-SQL)
ISNULL (Transact-SQL)
LIKE (Transact-SQL)
Logical Operator Precedence
Null Values
NULLIF (Transact-SQL)
Operator Precedence (Transact-SQL)
Module 3
Summarizing Data
Deterministic and Nondeterministic Functions
Aggregate Functions
COUNT (Transact-SQL)
CREATE AGGREGATE (Transact-SQL)
CLR User-Defined Aggregates
Invoking CLR User-Defined Aggregate Functions
GROUP BY (Transact-SQL)
HAVING (Transact-SQL)
COMPUTE (Transact-SQL)
GROUPING SETS Equivalents
Ranking Functions (Transact-SQL)
R-6 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
ROW_NUMBER (Transact-SQL)
NTILE (Transact-SQL)
Using PIVOT and UNPIVOT
SQL Server Overview
Module 4
PRIMARY KEY Constraints
Module 5
ALL (Transact-SQL)
OME | ANY (Transact-SQL)
Module 6
INSERT (Transact SQL)
Adding Rows by Using INSERT and SELECT
INSERT (Transact SQL)
INSERT (Transact SQL)
OUTPUT Clause (Transact-SQL)
DELETE (Transact-SQL)
TRUNCATE TABLE (Transact-SQL)
UPDATE (Transact-SQL)
Changing Data by Using UPDATE
Changing Data by Using the SET Clause
Changing Data by Using the FROM Clause
Changing Data by Using the WHERE Clause
Transactions (Database Engine)
Write-Ahead Transaction Log
Checkpoints and the Active Portion of the Log
Module 7
Managing Metadata in SQL Server
Compatibility Views (Transact-SQL)
Querying the SQL Server System Catalog
Information Schema Views (Transact-SQL)
Dynamic Management Views and Functions
Viewing Database Metadata
Understanding XML in SQL Server
Using XML Data Types
FOR XML Support for String Data Types
Using OPENXML
How to use XQuery to query XML data
Reporting Services Using XML and Web Service Data Sources
SQL Server 2008 Full-Text Search Internals and Enhancements
CONTAINS (Transact-SQL)
FREETEXT (Transact-SQL)
Full-Text Search Query Fundamentals
Integrating Full-Text Search and Transact-SQL Predicates
Module 8
SQL Views
CREATE VIEW (Transact-SQL)
Creating Indexed Views
Using Partitioned Views
User-defined Function Basics
CREATE FUNCTION (Transact-SQL)
CREATE PROCEDURE (Transact-SQL)
CREATE TRIGGER (Transact-SQL)
Distributed Queries
R-8 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Linking Servers
OPENROWSET (Transact-SQL)
sp_addlinkedserver (Transact-SQL)
Module 9
Execution Plans
Data Type Conversions
Implicit Conversions
Using CAST and CONVERT
Data Type Precedence
Using Time and Date Data
Date and Time Data Types and Functions
hierarchyid
Using the hierarchyid Data Type
Cursors (Database Engine)
Cursor Implementations
DECLARE CURSOR:
Using DEALLOCATE
JOIN Fundamentals
Manipulating Result Sets
Query Fundamentals
Dynamic SQL
sp_executesql
Using sp_executesql
EXECUTE
SQL Injection
SQL Injection Protection
Source Control Basics
Knowledge Base
This section includes content from Microsoft TechNet and MSDN that provides in-depth discussion on
technical topics related to SQL Server 2008
Knowledge Base
Query Tools
Microsoft
Schema Diagrams for the database can be found here:
http://www.codeplex.com/MSFTDBProdSamples/Wiki/View.aspx?title=AWSchemaDiag&referring
Title=Home
Communities
The Professional Association for SQL Server (PASS) is an independent, not-for-profit association, dedicated
to supporting, educating, and promoting the Microsoft SQL Server community. Offering a multitude of
networking channels from local user groups and special interest groups (SIGs) to webcasts and the annual
PASS Summit the largest gathering of SQL Server professionals in the world PASS enables knowledge
sharing, in-depth learning, access to the Microsoft SQL Server team, and the ability to influence the
direction of SQL Server technologies.
For more information and your free membership, visit www.sqlpass.org.
Blogs
Query Processing -- introduction to the blog!
Writing Queries Using Microsoft SQL Server 2008 Transact-SQL R-11
Books
This section describes the various books that may be of use to SQL Server 2008 DBAs.
Introducing Microsoft SQL Server 2008, Microsoft Corporation, Peter DeBetta
R-12 Writing Queries Using Microsoft SQL Server 2008 Transact-SQL
Note Not all training products will have a Knowledge Base article if that is the case, please ask
your instructor whether or not there are existing error log entries.
Courseware Feedback
Send all courseware feedback to support@mscourseware.com. We truly appreciate your time and effort.
We review every e-mail received and forward the information on to the appropriate team. Unfortunately,
because of volume, we are unable to provide a response but we may use your feedback to improve your
future experience with Microsoft Learning products.
Reporting Errors
When providing feedback, include the training product name and number in the subject line of your e-
mail. When you provide comments or report bugs, please include the following:
Document
Page number or location
Complete description of the error or suggested change
Please provide any details that are necessary to help us verify the issue.
Important All errors and suggestions are evaluated, but only those that are validated are added
to the product Knowledge Base article.