Professional Documents
Culture Documents
10776A ENU TrainerHandbook Part2
10776A ENU TrainerHandbook Part2
10776A ENU TrainerHandbook Part2
10776A
Developing Microsoft ®
SQL Server 2012 ®
Databases
MCT USE ONLY. STUDENT USE PROHIBITED
ii Developing Microsoft® SQL Server® 2012 Databases
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.
© 2012 Microsoft Corporation. All rights reserved.
Released: 05/2012
MCT USE ONLY. STUDENT USE PROHIBITED
MICROSOFT LICENSE TERMS
OFFICIAL MICROSOFT LEARNING PRODUCTS
MICROSOFT OFFICIAL COURSE Pre-Release and Final Release Versions
These license terms are an agreement between Microsoft Corporation and you. Please read them. They apply to
the Licensed Content named above, which includes the media on which you received it, if any. These license
terms also apply to any updates, supplements, internet based services and support services for the Licensed
Content, unless other terms accompany those items. If so, those terms apply.
BY DOWNLOADING OR USING THE LICENSED CONTENT, YOU ACCEPT THESE TERMS. IF YOU DO NOT ACCEPT
THEM, DO NOT DOWNLOAD OR USE THE LICENSED CONTENT.
If you comply with these license terms, you have the rights below.
1. DEFINITIONS.
a. “Authorized Learning Center” means a Microsoft Learning Competency Member, Microsoft IT Academy
Program Member, or such other entity as Microsoft may designate from time to time.
b. “Authorized Training Session” means the Microsoft-authorized instructor-led training class using only
MOC Courses that are conducted by a MCT at or through an Authorized Learning Center.
c. “Classroom Device” means one (1) dedicated, secure computer that you own or control that meets or
exceeds the hardware level specified for the particular MOC Course located at your training facilities or
primary business location.
d. “End User” means an individual who is (i) duly enrolled for an Authorized Training Session or Private
Training Session, (ii) an employee of a MPN Member, or (iii) a Microsoft full-time employee.
e. “Licensed Content” means the MOC Course and any other content accompanying this agreement.
Licensed Content may include (i) Trainer Content, (ii) sample code, and (iii) associated media.
f. “Microsoft Certified Trainer” or “MCT” means an individual who is (i) engaged to teach a training session
to End Users on behalf of an Authorized Learning Center or MPN Member, (ii) currently certified as a
Microsoft Certified Trainer under the Microsoft Certification Program, and (iii) holds a Microsoft
Certification in the technology that is the subject of the training session.
g. “Microsoft IT Academy Member” means a current, active member of the Microsoft IT Academy
Program.
h. “Microsoft Learning Competency Member” means a Microsoft Partner Network Program Member in
good standing that currently holds the Learning Competency status.
i. “Microsoft Official Course” or “MOC Course” means the Official Microsoft Learning Product instructor-
led courseware that educates IT professionals or developers on Microsoft technologies.
MCT USE ONLY. STUDENT USE PROHIBITED
j. “Microsoft Partner Network Member” or “MPN Member” means a silver or gold-level Microsoft Partner
Network program member in good standing.
k. “Personal Device” means one (1) device, workstation or other digital electronic device that you
personally own or control that meets or exceeds the hardware level specified for the particular MOC
Course.
l. “Private Training Session” means the instructor-led training classes provided by MPN Members for
corporate customers to teach a predefined learning objective. These classes are not advertised or
promoted to the general public and class attendance is restricted to individuals employed by or
contracted by the corporate customer.
m. “Trainer Content” means the trainer version of the MOC Course and additional content designated
solely for trainers to use to teach a training session using a MOC Course. Trainer Content may include
Microsoft PowerPoint presentations, instructor notes, lab setup guide, demonstration guides, beta
feedback form and trainer preparation guide for the MOC Course. To clarify, Trainer Content does not
include virtual hard disks or virtual machines.
2. INSTALLATION AND USE RIGHTS. The Licensed Content is licensed not sold. The Licensed Content is
licensed on a one copy per user basis, such that you must acquire a license for each individual that
accesses or uses the Licensed Content.
2.1 Below are four separate sets of installation and use rights. Only one set of rights apply to you.
ii. Use of Instructional Components in Trainer Content. You may customize, in accordance with the
most recent version of the MCT Agreement, those portions of the Trainer Content that are logically
associated with instruction of a training session. If you elect to exercise the foregoing rights, you
agree: (a) that any of these customizations will only be used for providing a training session, (b) any
customizations will comply with the terms and conditions for Modified Training Sessions and
Supplemental Materials in the most recent version of the MCT agreement and with this agreement.
For clarity, any use of “customize” refers only to changing the order of slides and content, and/or
not using all the slides or content, it does not mean changing or modifying any slide or content.
2.2 Separation of Components. The Licensed Content components are licensed as a single unit and you
may not separate the components and install them on different devices.
2.4 Third Party Programs. The Licensed Content may contain third party programs or services. These
license terms will apply to your use of those third party programs or services, unless other terms accompany
those programs and services.
2.5 Additional Terms. Some Licensed Content may contain components with additional terms,
conditions, and licenses regarding its use. Any non-conflicting terms in those conditions and licenses also
apply to that respective component and supplements the terms described in this Agreement.
3. PRE-RELEASE VERSIONS. If the Licensed Content is a pre-release (“beta”) version, in addition to the other
provisions in this agreement, then these terms also apply:
a. Pre-Release Licensed Content. This Licensed Content is a pre-release version. It may not contain the
same information and/or work the way a final version of the Licensed Content will. We may change it
for the final version. We also may not release a final version. Microsoft is under no obligation to
provide you with any further content, including the final release version of the Licensed Content.
b. Feedback. If you agree to give feedback about the Licensed Content to Microsoft, either directly or
through its third party designee, you give to Microsoft without charge, the right to use, share and
commercialize your feedback in any way and for any purpose. You also give to third parties, without
charge, any patent rights needed for their products, technologies and services to use or interface with
any specific parts of a Microsoft software, Microsoft product, or service that includes the feedback. You
will not give feedback that is subject to a license that requires Microsoft to license its software,
technologies, or products to third parties because we include your feedback in them. These rights
MCT USE ONLY. STUDENT USE PROHIBITED
survive this agreement.
c. Term. If you are an Authorized Training Center, MCT or MPN, you agree to cease using all copies of the
beta version of the Licensed Content upon (i) the date which Microsoft informs you is the end date for
using the beta version, or (ii) sixty (60) days after the commercial release of the Licensed Content,
whichever is earliest (“beta term”). Upon expiration or termination of the beta term, you will
irretrievably delete and destroy all copies of same in the possession or under your control.
4. INTERNET-BASED SERVICES. Classroom Devices located at Authorized Learning Center’s physical location
may contain virtual machines and virtual hard disks for use while attending an Authorized Training
Session. You may only use the software on the virtual machines and virtual hard disks on a Classroom
Device solely to perform the virtual lab activities included in the MOC Course while attending the
Authorized Training Session. Microsoft may provide Internet-based services with the software included
with the virtual machines and virtual hard disks. It may change or cancel them at any time. If the
software is pre-release versions of software, some of its Internet-based services may be turned on by
default. The default setting in these versions of the software do not necessarily reflect how the features
will be configured in the commercially released versions. If Internet-based services are included with the
software, they are typically simulated for demonstration purposes in the software and no transmission
over the Internet takes place. However, should the software be configured to transmit over the Internet,
the following terms apply:
a. Consent for Internet-Based Services. The software features described below connect to Microsoft or
service provider computer systems over the Internet. In some cases, you will not receive a separate
notice when they connect. You may switch off these features or not use them. By using these features,
you consent to the transmission of this information. Microsoft does not use the information to identify
or contact you.
b. Computer Information. The following features use Internet protocols, which send to the appropriate
systems computer information, such as your Internet protocol address, the type of operating system,
browser and name and version of the software you are using, and the language code of the device
where you installed the software. Microsoft uses this information to make the Internet-based services
available to you.
• Accelerators. When you use click on or move your mouse over an Accelerator, the title and full web
address or URL of the current webpage, as well as standard computer information, and any content
you have selected, might be sent to the service provider. If you use an Accelerator provided by
Microsoft, the information sent is subject to the Microsoft Online Privacy Statement, which is
available at go.microsoft.com/fwlink/?linkid=31493. If you use an Accelerator provided by a third
party, use of the information sent will be subject to the third party’s privacy practices.
• Automatic Updates. This software contains an Automatic Update feature that is on by default. For
more information about this feature, including instructions for turning it off, see
go.microsoft.com/fwlink/?LinkId=178857. You may turn off this feature while the software is
running (“opt out”). Unless you expressly opt out of this feature, this feature will (a) connect to
Microsoft or service provider computer systems over the Internet, (b) use Internet protocols to send
to the appropriate systems standard computer information, such as your computer’s Internet
protocol address, the type of operating system, browser and name and version of the software you
are using, and the language code of the device where you installed the software, and (c)
automatically download and install, or prompt you to download and/or install, current Updates to
the software. In some cases, you will not receive a separate notice before this feature takes effect.
MCT USE ONLY. STUDENT USE PROHIBITED
By installing the software, you consent to the transmission of standard computer information and
the automatic downloading and installation of updates.
• Auto Root Update. The Auto Root Update feature updates the list of trusted certificate authorities.
you can switch off the Auto Root Update feature.
• Customer Experience Improvement Program (CEIP), Error and Usage Reporting; Error Reports. This
software uses CEIP and Error and Usage Reporting components enabled by default that
automatically send to Microsoft information about your hardware and how you use this software.
This software also automatically sends error reports to Microsoft that describe which software
components had errors and may also include memory dumps. You may choose not to use these
software components. For more information please go to
<http://go.microsoft.com/fwlink/?LinkID=196910>.
• Digital Certificates. The software uses digital certificates. These digital certificates confirm the
identity of Internet users sending X.509 standard encrypted information. They also can be used to
digitally sign files and macros, to verify the integrity and origin of the file contents. The software
retrieves certificates and updates certificate revocation lists. These security features operate only
when you use the Internet.
• Extension Manager. The Extension Manager can retrieve other software through the internet from
the Visual Studio Gallery website. To provide this other software, the Extension Manager sends to
Microsoft the name and version of the software you are using and language code of the device
where you installed the software. This other software is provided by third parties to Visual Studio
Gallery. It is licensed to users under terms provided by the third parties, not from Microsoft. Read
the Visual Studio Gallery terms of use for more information.
• IPv6 Network Address Translation (NAT) Traversal service (Teredo). This feature helps existing
home Internet gateway devices transition to IPv6. IPv6 is a next generation Internet protocol. It
helps enable end-to-end connectivity often needed by peer-to-peer applications. To do so, each
time you start up the software the Teredo client service will attempt to locate a public Teredo
Internet service. It does so by sending a query over the Internet. This query only transfers standard
Domain Name Service information to determine if your computer is connected to the Internet and
can locate a public Teredo service. If you
· use an application that needs IPv6 connectivity or
· configure your firewall to always enable IPv6 connectivity
by default standard Internet Protocol information will be sent to the Teredo service at Microsoft at
regular intervals. No other information is sent to Microsoft. You can change this default to use non-
Microsoft servers. You can also switch off this feature using a command line utility named “netsh”.
• Malicious Software Removal. During setup, if you select “Get important updates for installation”,
the software may check and remove certain malware from your device. “Malware” is malicious
software. If the software runs, it will remove the Malware listed and updated at
www.support.microsoft.com/?kbid=890830. During a Malware check, a report will be sent to
Microsoft with specific information about Malware detected, errors, and other information about
your device. This information is used to improve the software and other Microsoft products and
services. No information included in these reports will be used to identify or contact you. You may
disable the software’s reporting functionality by following the instructions found at
MCT USE ONLY. STUDENT USE PROHIBITED
www.support.microsoft.com/?kbid=890830. For more information, read the Windows Malicious
Software Removal Tool privacy statement at go.microsoft.com/fwlink/?LinkId=113995.
• Microsoft Digital Rights Management. If you use the software to access content that has been
protected with Microsoft Digital Rights Management (DRM), then, in order to let you play the
content, the software may automatically request media usage rights from a rights server on the
Internet and download and install available DRM updates. For more information, see
go.microsoft.com/fwlink/?LinkId=178857.
• Microsoft Telemetry Reporting Participation. If you choose to participate in Microsoft Telemetry
Reporting through a “basic” or “advanced” membership, information regarding filtered URLs,
malware and other attacks on your network is sent to Microsoft. This information helps Microsoft
improve the ability of Forefront Threat Management Gateway to identify attack patterns and
mitigate threats. In some cases, personal information may be inadvertently sent, but Microsoft will
not use the information to identify or contact you. You can switch off Telemetry Reporting. For
more information on this feature, see http://go.microsoft.com/fwlink/?LinkId=130980.
• Microsoft Update Feature. To help keep the software up-to-date, from time to time, the software
connects to Microsoft or service provider computer systems over the Internet. In some cases, you
will not receive a separate notice when they connect. When the software does so, we check your
version of the software and recommend or download updates to your devices. You may not receive
notice when we download the update. You may switch off this feature.
• Network Awareness. This feature determines whether a system is connected to a network by either
passive monitoring of network traffic or active DNS or HTTP queries. The query only transfers
standard TCP/IP or DNS information for routing purposes. You can switch off the active query
feature through a registry setting.
• Plug and Play and Plug and Play Extensions. You may connect new hardware to your device, either
directly or over a network. Your device may not have the drivers needed to communicate with that
hardware. If so, the update feature of the software can obtain the correct driver from Microsoft and
install it on your device. An administrator can disable this update feature.
• Real Simple Syndication (“RSS”) Feed. This software start page contains updated content that is
supplied by means of an RSS feed online from Microsoft.
• Search Suggestions Service. When you type a search query in Internet Explorer by using the Instant
Search box or by typing a question mark (?) before your search term in the Address bar, you will see
search suggestions as you type (if supported by your search provider). Everything you type in the
Instant Search box or in the Address bar when preceded by a question mark (?) is sent to your
search provider as you type it. In addition, when you press Enter or click the Search button, all the
text that is in the search box or Address bar is sent to the search provider. If you use a Microsoft
search provider, the information you send is subject to the Microsoft Online Privacy Statement,
which is available at go.microsoft.com/fwlink/?linkid=31493. If you use a third-party search
provider, use of the information sent will be subject to the third party’s privacy practices. You can
turn search suggestions off at any time in Internet Explorer by using Manage Add-ons under the
Tools button. For more information about the search suggestions service, see
go.microsoft.com/fwlink/?linkid=128106.
• SQL Server Reporting Services Map Report Item. The software may include features that retrieve
content such as maps, images and other data through the Bing Maps (or successor branded)
MCT USE ONLY. STUDENT USE PROHIBITED
application programming interface (the “Bing Maps APIs”). The purpose of these features is to
create reports displaying data on top of maps, aerial and hybrid imagery. If these features are
included, you may use them to create and view dynamic or static documents. This may be done only
in conjunction with and through methods and means of access integrated in the software. You may
not otherwise copy, store, archive, or create a database of the content available through the Bing
Maps APIs. you may not use the following for any purpose even if they are available through the
Bing Maps APIs:
• Bing Maps APIs to provide sensor based guidance/routing, or
• Any Road Traffic Data or Bird’s Eye Imagery (or associated metadata).
Your use of the Bing Maps APIs and associated content is also subject to the additional terms and
conditions at http://www.microsoft.com/maps/product/terms.html.
• URL Filtering. The URL Filtering feature identifies certain types of web sites based upon predefined
URL categories, and allows you to deny access to such web sites, such as known malicious sites and
sites displaying inappropriate or pornographic materials. To apply URL filtering, Microsoft queries
the online Microsoft Reputation Service for URL categorization. You can switch off URL filtering. For
more information on this feature, see http://go.microsoft.com/fwlink/?LinkId=130980
• Web Content Features. Features in the software can retrieve related content from Microsoft and
provide it to you. To provide the content, these features send to Microsoft the type of operating
system, name and version of the software you are using, type of browser and language code of the
device where you run the software. Examples of these features are clip art, templates, online
training, online assistance and Appshelp. You may choose not to use these web content features.
• Windows Media Digital Rights Management. Content owners use Windows Media digital rights
management technology (WMDRM) to protect their intellectual property, including copyrights. This
software and third party software use WMDRM to play and copy WMDRM-protected content. If the
software fails to protect the content, content owners may ask Microsoft to revoke the software’s
ability to use WMDRM to play or copy protected content. Revocation does not affect other content.
When you download licenses for protected content, you agree that Microsoft may include a
revocation list with the licenses. Content owners may require you to upgrade WMDRM to access
their content. Microsoft software that includes WMDRM will ask for your consent prior to the
upgrade. If you decline an upgrade, you will not be able to access content that requires the upgrade.
You may switch off WMDRM features that access the Internet. When these features are off, you can
still play content for which you have a valid license.
• Windows Media Player. When you use Windows Media Player, it checks with Microsoft for
· compatible online music services in your region;
· new versions of the player; and
· codecs if your device does not have the correct ones for playing content.
You can switch off this last feature. For more information, go to
www.microsoft.com/windows/windowsmedia/player/11/privacy.aspx.
• Windows Rights Management Services. The software contains a feature that allows you to create
content that cannot be printed, copied or sent to others without your permission. For more
information, go to www.microsoft.com/rms. you may choose not to use this feature
MCT USE ONLY. STUDENT USE PROHIBITED
• Windows Time Service. This service synchronizes with time.windows.com once a week to provide
your computer with the correct time. You can turn this feature off or choose your preferred time
source within the Date and Time Control Panel applet. The connection uses standard NTP protocol.
• Windows Update Feature. You may connect new hardware to the device where you run the
software. Your device may not have the drivers needed to communicate with that hardware. If so,
the update feature of the software can obtain the correct driver from Microsoft and run it on your
device. You can switch off this update feature.
c. Use of Information. Microsoft may use the device information, error reports, and malware reports to
improve our software and services. We may also share it with others, such as hardware and software
vendors. They may use the information to improve how their products run with Microsoft software.
d. Misuse of Internet-based Services. You may not use any Internet-based service in any way that could
harm it or impair anyone else’s use of it. You may not use the service to try to gain unauthorized access
to any service, data, account or network by any means.
5. SCOPE OF LICENSE. The Licensed Content is licensed, not sold. This agreement only gives you some rights
to use the Licensed Content. Microsoft reserves all other rights. Unless applicable law gives you more
rights despite this limitation, you may use the Licensed Content only as expressly permitted in this
agreement. In doing so, you must comply with any technical limitations in the Licensed Content that only
allows you to use it in certain ways. Except as expressly permitted in this agreement, you may not:
• install more copies of the Licensed Content on devices than the number of licenses you acquired;
• allow more individuals to access the Licensed Content than the number of licenses you acquired;
• publicly display, or make the Licensed Content available for others to access or use;
• install, sell, publish, transmit, encumber, pledge, lend, copy, adapt, link to, post, rent, lease or lend,
make available or distribute the Licensed Content to any third party, except as expressly permitted
by this Agreement.
• reverse engineer, decompile, remove or otherwise thwart any protections or disassemble the
Licensed Content except and only to the extent that applicable law expressly permits, despite this
limitation;
• access or use any Licensed Content for which you are not providing a training session to End Users
using the Licensed Content;
• access or use any Licensed Content that you have not been authorized by Microsoft to access and
use; or
• transfer the Licensed Content, in whole or in part, or assign this agreement to any third party.
6. RESERVATION OF RIGHTS AND OWNERSHIP. Microsoft reserves all rights not expressly granted to you in
this agreement. The Licensed Content is protected by copyright and other intellectual property laws and
treaties. Microsoft or its suppliers own the title, copyright, and other intellectual property rights in the
Licensed Content. You may not remove or obscure any copyright, trademark or patent notices that
appear on the Licensed Content or any components thereof, as delivered to you.
7. EXPORT RESTRICTIONS. The Licensed Content is subject to United States export laws and regulations. You
must comply with all domestic and international export laws and regulations that apply to the Licensed
Content. These laws include restrictions on destinations, End Users and end use. For additional
information, see www.microsoft.com/exporting.
MCT USE ONLY. STUDENT USE PROHIBITED
8. LIMITATIONS ON SALE, RENTAL, ETC. AND CERTAIN ASSIGNMENTS. You may not sell, rent, lease, lend or
sublicense the Licensed Content or any portion thereof, or transfer or assign this agreement.
9. SUPPORT SERVICES. Because the Licensed Content is “as is”, we may not provide support services for it.
10. TERMINATION. Without prejudice to any other rights, Microsoft may terminate this agreement if you fail
to comply with the terms and conditions of this agreement. Upon any termination of this agreement, you
agree to immediately stop all use of and to irretrievable delete and destroy all copies of the Licensed
Content in your possession or under your control.
11. LINKS TO THIRD PARTY SITES. You may link to third party sites through the use of the Licensed Content.
The third party sites are not under the control of Microsoft, and Microsoft is not responsible for the
contents of any third party sites, any links contained in third party sites, or any changes or updates to third
party sites. Microsoft is not responsible for webcasting or any other form of transmission received from
any third party sites. Microsoft is providing these links to third party sites to you only as a convenience,
and the inclusion of any link does not imply an endorsement by Microsoft of the third party site.
12. ENTIRE AGREEMENT. This agreement, and the terms for supplements, updates and support services are
the entire agreement for the Licensed Content.
b. Outside the United States. If you acquired the Licensed Content in any other country, the laws of that
country apply.
14. LEGAL EFFECT. This agreement describes certain legal rights. You may have other rights under the laws of
your country. You may also have rights with respect to the party from whom you acquired the Licensed
Content. This agreement does not change your rights under the laws of your country if the laws of your
country do not permit it to do so.
15. DISCLAIMER OF WARRANTY. THE LICENSED CONTENT IS LICENSED "AS-IS," "WITH ALL FAULTS," AND "AS
AVAILABLE." YOU BEAR THE RISK OF USING IT. MICROSOFT CORPORATION AND ITS RESPECTIVE
AFFILIATES GIVE NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS UNDER OR IN RELATION TO
THE LICENSED CONTENT. YOU MAY HAVE ADDITIONAL CONSUMER RIGHTS UNDER YOUR LOCAL LAWS
WHICH THIS AGREEMENT CANNOT CHANGE. TO THE EXTENT PERMITTED UNDER YOUR LOCAL LAWS,
MICROSOFT CORPORATION AND ITS RESPECTIVE AFFILIATES EXCLUDE ANY IMPLIED WARRANTIES OR
CONDITIONS, INCLUDING THOSE OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NON-INFRINGEMENT.
16. LIMITATION ON AND EXCLUSION OF REMEDIES AND DAMAGES. TO THE EXTENT NOT PROHIBITED BY
LAW, YOU CAN RECOVER FROM MICROSOFT CORPORATION AND ITS SUPPLIERS ONLY DIRECT
DAMAGES UP TO USD$5.00. YOU AGREE NOT TO SEEK TO RECOVER ANY OTHER DAMAGES, INCLUDING
CONSEQUENTIAL, LOST PROFITS, SPECIAL, INDIRECT OR INCIDENTAL DAMAGES FROM MICROSOFT
CORPORATION AND ITS RESPECTIVE SUPPLIERS.
MCT USE ONLY. STUDENT USE PROHIBITED
This limitation applies to
o anything related to the Licensed Content, services made available through the Licensed Content, or
content (including code) on third party Internet sites or third-party programs; and
o claims for breach of contract, breach of warranty, guarantee or condition, strict liability, negligence,
or other tort to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The
above limitation or exclusion may not apply to you because your country may not allow the exclusion or
limitation of incidental, consequential or other damages.
Please note: As this Licensed Content is distributed in Quebec, Canada, some of the clauses in this agreement
are provided below in French.
Remarque : Ce le contenu sous licence étant distribué au Québec, Canada, certaines des clauses dans ce
contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le contenu sous licence visé par une licence est offert « tel quel ». Toute
utilisation de ce contenu sous licence est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie
expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection dues
consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties
implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage.
Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects,
accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera
pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus
par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays
si celles-ci ne le permettent pas.
Acknowledgments
Microsoft Learning would like to acknowledge and thank the following for their contribution towards
developing this title. Their effort at various stages in the development has ensured that you have a good
classroom experience.
Contents
Module 1: Introduction to SQL Server 2012 and its Toolset
Lesson 1: Introduction to the SQL Server Platform 1-3
Lesson 2: Working with SQL Server Tools 1-14
Lesson 3: Configuring SQL Server Services 1-25
Lab 1: Introduction to SQL Server and its Toolset 1-33
Module 10
Designing and Implementing Stored Procedures
Contents:
Lesson 1: Introduction to Stored Procedures 10-3
Lesson 2: Working With Stored Procedures 10-11
Lesson 3: Implementing Parameterized Stored Procedures 10-22
Lesson 4: Controlling Execution Context 10-31
Lab 10: Designing and Implementing Stored Procedures 10-37
MCT USE ONLY. STUDENT USE PROHIBITED
10-2 Designing and Implementing Stored Procedures
Module Overview
Stored procedures allow the creation of T-SQL logic that will be stored and executed at the server. This
logic might enforce business rules or data consistency. Stored procedures are also used to return sets of
rows based upon input parameters. You will see the potential advantages of the use of stored procedures
in this module along with guidelines on creating them.
Objectives
After completing this module, you will be able to:
• Describe the role of stored procedures and the potential benefits of using them
• Work with stored procedures
Lesson 1
Introduction to Stored Procedures
Microsoft® SQL Server® provides a number of stored procedures and users can also create stored
procedures. In this lesson, you will see the role of stored procedures and the potential benefits of using
them. System stored procedures provide a large amount of pre-built functionality that you can take
advantage of when building applications. It is also important to realize when designing stored procedures
that not all T-SQL statements are permitted within stored procedures.
Objectives
After completing this lesson, you will be able to:
• Describe the role of stored procedures
• Identify statements that are not permitted within the body of a stored procedure declaration
MCT USE ONLY. STUDENT USE PROHIBITED
10-4 Designing and Implementing Stored Procedures
Key Points
A stored procedure is a named collection of Transact-SQL statements that is stored on the server within
the database itself. Stored procedures are a method of encapsulating repetitive tasks; they support user-
declared variables, conditional execution, and other powerful programming features.
Alternately, a stored procedure could be created at the server level to encapsulate all the T-SQL
statements required. Stored procedures are given names and are called by name. The application can
then simply ask to execute the stored procedure each time it needs to use that same functionality, rather
than sending all the statements that would otherwise be required.
Stored Procedures
Stored procedures are similar to procedures, methods and functions in high-level languages. They can
have input and output parameters and a return value.
As a side effect of executing the stored procedure, rows of data can also be returned from the stored
procedure. In fact, multiple rowsets can be returned from a single stored procedure.
Stored procedures can be created in either T-SQL or in managed .NET code and are run by the EXECUTE
T-SQL statement. The creation of stored procedures in managed code will be discussed in Module 16.
Question: Why might it be useful to return multiple rowsets from a stored procedure?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-5
Key Points
The use of stored procedures offers a number of benefits over issuing T-SQL code directly from an
application.
Security Boundary
Stored procedures can be part of a scheme that helps increase application security. They can be treated as
a security boundary. Users can be given permission to execute a stored procedure without being given
permission to access the objects that the stored procedure accesses.
For example, you can give a user (or set of users via a role) permission to execute a stored procedure that
updates a table without granting the user any permissions at all directly on the table.
Modular Programming
Code reuse is important. Stored procedures help by allowing logic to be created once and then to be
called many times and from many applications. Maintenance is easier as if a change is needed, you only
need to change the procedure, without needing to change the application code at all in many cases.
Changing a stored procedure could avoid the need to change the data access logic in a group of
applications.
Delayed Binding
It is possible to create a stored procedure that accesses (or references) a database object that does not yet
exist. This can be helpful in simplifying the order that database objects need to be created in. This is
referred to as deferred name resolution.
MCT USE ONLY. STUDENT USE PROHIBITED
10-6 Designing and Implementing Stored Procedures
Performance
Send the name of a stored procedure to be executed rather than hundreds or thousands of lines of
executable T-SQL code can offer a significant reduction in the level of network traffic.
Before T-SQL code is executed, it needs to be compiled. When a stored procedure is compiled, in many
cases SQL Server will attempt to retain (and reuse) the query plan that it previously generated, to avoid
the cost of the compilation of the code.
While reuse of execution plans for ad-hoc T-SQL code issued by applications is possible, SQL Server favors
the reuse of stored procedure execution plans. Query plans for ad-hoc T-SQL statements are amongst the
first items removed from memory when memory pressure is occurring.
The rules governing the reuse of query plans for ad-hoc T-SQL are largely based on matching the text of
the queries exactly. Any difference at all (eg: whitespace, casing, etc.) will cause a different query plan to
be used, unless the difference is only a value that SQL Server decides must be the equivalent of a
parameter.
Stored procedures have a much higher chance of achieving query plan reuse.
Question: Stored procedures can be created in any order. What could cause the tables that are
referenced by the stored procedures to need to be created in a specific order?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-7
Key Points
SQL Server is supplied with a large amount of pre-built functionality shipped within system stored
procedures and system extended stored procedures.
Originally, there was a basic distinction in the naming where system stored procedures had an sp_ prefix
and system extended stored procedures had an xp_ prefix. Over time, the need to maintain backwards
compatibility has caused a mixture of these prefixes to appear in both types. Now, most system stored
procedures have an sp_ prefix and most system extended stored procedures have an xp_ prefix.
System stored procedures are created within the sys schema. Examples of system stored procedures are
sys.sp_configure, sys.sp_addmessage, sys.sp_executesql.
MCT USE ONLY. STUDENT USE PROHIBITED
10-8 Designing and Implementing Stored Procedures
Managed code stored procedures should now be used instead of user-defined extended stored
procedures. The use of managed code to create stored procedures will be described in Module 16.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-9
Key Points
Not all T-SQL statements are permitted within stored procedure declarations. The table on the slide shows
the statements that cannot be used.
Demonstration Steps
1. Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_10_PRJ\10776A_10_PRJ.ssmssln and click Open.
3. From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file from
within Solution Explorer.
4. Open the 11 – Demonstration 1A.sql script file.
5. Follow the instructions contained within the comments of the script file.
Question: What does the mismatch of prefixes in system stored procedure and system extended
stored procedure names suggest?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-11
Lesson 2
Working with Stored Procedures
Now that you have an understanding of why stored procedures are important, you need to gain an
understanding of the practicalities involved in working with stored procedures.
Objectives
After completing this lesson, you will be able to:
Key Points
The T-SQL CREATE PROCEDURE statement is used to create new procedures.
CREATE PROCEDURE is commonly abbreviated to CREATE PROC. A procedure cannot be replaced by
using the CREATE PROC statement. It needs to be explicitly altered using an ALTER PROC statement or
dropped and then recreated.
The CREATE PROC statement must be the only statement in the T-SQL batch. All statements from the
keyword AS until the end of the script or until the end of the batch (using a batch separator such as GO)
will become part of the body of the stored procedure. Creating a stored procedure requires both the
CREATE PROCEDURE permission in the current database and the ALTER permission on the schema in
which the procedure is being created. It is important to keep connection settings such as
QUOTED_IDENTIFIER and ANSI_NULLS consistent when working with stored procedures. The settings
associated with the stored procedure are taken from the settings in the session where it is created.
Stored procedures are always created in the current database with the single exception of stored
procedures created with a # prefix in their name. The # prefix on a name indicates that it is a temporary
object. As such, it would be created in the tempdb database and removed at the end of the user's session.
Debugging Stored Procedures
A good practice when working with stored procedures is to first write and test the T-SQL statements that
you want to include in your stored procedure and if you receive the results you expected, then wrap the
T-SQL statements in a CREATE PROCEDURE statement.
Question: What does this stored procedure do that a similar view definition could not?
Note: Even though wrapping the body of a stored procedure with a BEGIN…END block is
not required, doing so is considered a good practice. Note also that the execution of a stored
procedure can be terminated by the execution of a RETURN statement within the stored
procedure.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-13
Key Points
The T-SQL EXECUTE statement is used to execute stored procedures. The EXECUTE statement is
commonly abbreviated as EXEC.
EXECUTE Statement
The EXECUTE is mostly used to execute stored procedures but can also be used to execute other objects
such as dynamic SQL statements.
As mentioned in the first lesson, system stored procedures can be executed within the master database
without having to explicitly refer to that database. That does not apply to other stored procedures.
If you use only the name of a table, SQL Server will first search in your default schema for the table and
then if it did not locate a table with that name, it will search the dbo schema for a table with that name.
This minimizes SQL Server's options for query plan reuse because it does not know until the moment the
stored procedure is executed which objects it needs to refer to as different users can have different
default schemas.
MCT USE ONLY. STUDENT USE PROHIBITED
10-14 Designing and Implementing Stored Procedures
If the stored procedure name starts with sp_ (not recommended for user stored procedures):
• SQL Server first looks in the master database in the sys schema for the stored procedure.
• SQL Server then looks in the default schema for the user executing the stored procedure.
• SQL Server then looks in the dbo schema in the current database for the stored procedure.
Having SQL Server perform unnecessary steps to locate a stored procedure reduces performance for
no reason.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-15
Key Points
The T-SQL ALTER PROCEDURE statement is used to replace an existing procedure. ALTER PROCEDURE is
often abbreviated to ALTER PROC.
ALTER PROC
The main reason for using the ALTER PROC statement is to retain any existing permissions on the
procedure while it is being changed. Users may have been granted permission to execute the procedure.
If you drop the procedure and recreate it, those permissions that had been granted to the users would be
removed when the procedure was dropped.
Procedure Type
Note that the type of procedure cannot be changed. For example, a T-SQL procedure cannot be changed
to a managed code procedure via an ALTER PROCEDURE statement or vice-versa.
Connection Settings
The connection settings such as QUOTED_IDENTIFIER and ANSI_NULLS that will be associated with the
modified stored procedure will be those taken from the session that makes the change, not from the
original stored procedure so it is important to keep these consistent when making changes.
Complete Replacement
Note that when you alter a stored procedure, you need to supply again any options (such as WITH
ENCRYPTION) that were supplied while creating the procedure. None of these options are retained and
they are replaced by whatever options are supplied in the ALTER PROC statement.
MCT USE ONLY. STUDENT USE PROHIBITED
10-16 Designing and Implementing Stored Procedures
Key Points
Dropping a stored procedure is straightforward. The DROP PROCEDURE statement is used to drop a
stored procedure and is commonly abbreviated as DROP PROC.
Permissions
Dropping a procedure requires either ALTER permission on the schema that the procedure is part of or
CONTROL permission on the procedure itself.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-17
Key Points
Before dropping a stored procedure, it is a good idea to check for any other objects that are dependent
upon the stored procedure.
sp_depends
Earlier versions of SQL Server used the sp_depends system stored procedure to return details of
dependencies between objects. It was known to have issues and to report incomplete information due to
issues with deferred name resolution.
sys.sql_expression_dependencies
Use of the sys.sql_expression_dependencies view replaces the previous use of the sp_depends system
stored procedure. Sys.sql_expression_dependencies provide a one row per name dependency on user-
defined entities in the current database. sys.dm_sql_referenced_entities and
sys.dm_sql_referencing_entities provide more targeted views over the data provided by
sys.sql_expression_dependencies.
You will see an example of these dependency views being used in the next demonstration.
MCT USE ONLY. STUDENT USE PROHIBITED
10-18 Designing and Implementing Stored Procedures
Key Points
There are a number of important guidelines that should be considered when creating stored procedures.
It is important to have a consistent way of naming your stored procedures. For example, some people use
a naming convention that is based on the use of a table name followed by an action. However, this does
not work well for more complex procedures that affect multiple tables. Others use an action verb followed
by a description of the action to be performed.
There is no right or wrong way to do this in all situations but you should decide on a method for naming
objects that are to be used in your applications and to apply the method consistently. It is possible via
Policy Based Management (first introduced in SQL Server 2008 and beyond the scope of this course) or
via DDL triggers (first introduced in SQL Server 2005 and also beyond the scope of this course) to enforce
naming conventions on most objects.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-19
Key Points
SQL Server provides an option to obfuscate the definition of stored procedures via the WITH
ENCRYPTION option. Caution needs to be exhibited in using it as it makes working with the application
more difficult and likely does not achieve the aims it is being targeted at.
WITH ENCRYPTION
As was mentioned in an earlier module dealing with views, it is very important to understand that while
SQL Server provides an option (WITH ENCRYPTION) to obfuscate the definition of your stored procedures,
that the encryption is not particularly strong.
It is known to be relatively easy to defeat as the encryption keys are stored in known locations within the
encrypted text. There are both direct methods and a number of third party tools that are capable of
reversing the encryption.
Original copies of the source need to be kept regardless of the fact that decryption might be possible. Do
not depend upon this.
Encrypted code is much harder to work with in terms of diagnosing and tuning performance issues.
Question: Why might you want to obfuscate the definition of a stored procedure?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-21
Demonstration Steps
1. If Demonstration 1A was not performed:
• Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
• In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_10_PRJ\10776A_10_PRJ.ssmssln and
click Open.
• From the View menu, click Solution Explorer. 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.
Question: How could the GetBlueProductsAndModels stored procedure be made more useful?
MCT USE ONLY. STUDENT USE PROHIBITED
10-22 Designing and Implementing Stored Procedures
Lesson 3
Implementing Parameterized Stored Procedures
The stored procedures that you have seen earlier in this module have not involved parameters. They have
produced their output without needing any input from the user and they have not returned any values
back apart from the rows that they have returned. Stored procedures are more flexible when you include
parameters as part of the procedure definition because you can create more generic application logic.
Stored procedures can use both input and output parameters and return values.
While the reuse of query execution plans is in general desirable, there are situations where this reuse is
detrimental. You will see situations where this can occur and consider options for workarounds to avoid
the detrimental outcomes.
Objectives
After completing this lesson, you will be able to:
• Explain the issues surrounding parameter sniffing and performance and the potential workarounds
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-23
Key Points
Parameterized stored procedures allow for a much higher level of code reuse. They contain 3 major
components: input parameters, output parameters and return values.
Input Parameters
Parameters are used to exchange data between stored procedures and the application or tool that called
the stored procedure. They allow the caller to pass a data value to the stored procedure. To define a
stored procedure that accepts input parameters, you declare one or more variables as parameters in the
CREATE PROCEDURE statement. You will see an example of this in the next topic.
Output Parameters
Output parameters allow the stored procedure to pass a data value or a cursor variable back to the caller.
To use an output parameter within Transact-SQL, you must specify the OUTPUT keyword in both the
CREATE PROCEDURE and the EXECUTE statements.
Return Value
Every stored procedure returns an integer return code to the caller. If the stored procedure does not
explicitly set a value for the return code, the return code is 0 if no error occurs, otherwise a negative value
is returned.
Return values are commonly used to return a status result or an error code from a procedure and are sent
by the T-SQL RETURN statement.
While it is possible to send a business-logic related value via a RETURN statement, in general, you should
use OUTPUT parameters to output values rather than the RETURN value.
MCT USE ONLY. STUDENT USE PROHIBITED
10-24 Designing and Implementing Stored Procedures
Key Points
Stored procedures can accept input parameters, similar to the way that parameters are passed to
functions or methods or subroutines in higher-level languages.
Input Parameters
Stored procedure parameters must have an @ prefix and must have a data type specified. The data type
will be checked when a call is made.
There are two ways to call a stored procedure with input parameters. One is to pass the parameters as a
list in the same order as in the CREATE PROCEDURE. The other is to pass a parameter name and value
pair. You cannot combine these two options in a single EXEC call.
Default Values
Provide default values for a parameter where appropriate. If a default is defined, a user can execute the
stored procedure without specifying a value for that parameter.
Look at the beginning of the procedure declaration from the example on the slide:
Two parameters have been defined (@DueDate and @Status). The @DueDate parameter has no default
value and must be supplied when the procedure is executed. The @Status parameter has a default value
of 5. If a value for the parameter is not supplied when the stored procedure is executed, then a value of 5
will be used.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-25
Validating parameters early avoids doing substantial work in the procedure and then having to undo all
that work.
This execution supplies a value for both @DueDate and for @Status. Note that the names of the
parameter have not been mentioned. SQL Server knows which parameter is which by its position in the
parameter list.
In this case, a value for the @DueDate parameter has been supplied but no value for the @Status
parameter has been supplied. In this case, the procedure will be executed with the @Status value set at a
default value of 5.
Finally, look at the third option:
In this case, the stored procedure is being called with both parameters but they are being identified by
name. Note that you could have also achieved the same outcome with the parameters specified in the
reverse order as they are identified by name:
Key Points
Output parameters are used very similarly to input parameters. While they are declared and used very
similarly to input parameters, output parameters have a few special requirements.
• The keyword OUTPUT must also be specified in the list of parameters passed during the EXEC
statement.
Look at the beginning of the procedure declaration from the example on the slide:
In this case, the @DueDate parameter is an input parameter and the @OrderCount parameter has been
specified as an output parameter. Note that in SQL Server there is no true equivalent of a .NET output
parameter. SQL Server output parameters are really input/output parameters.
First, variables to hold the parameter values have been declared. In this case, a variable to hold a due date
has been declared, along with another to hold the order count.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-27
In the EXEC call, note that the @OrderCount parameter is followed by the OUTPUT keyword. If you do not
specify the OUTPUT parameter in the EXEC statement, the stored procedure would still execute as normal,
including preparing a value to return in the output parameter. However, the output parameter value
would simply not be copied back into the @OrderCount variable. This is a common bug when working
with output parameters.
Finally, you would then use the returned value somehow in the business logic that follows the EXEC call.
Question: Why might you use output parameters in conjunction with IDENTITY columns?
MCT USE ONLY. STUDENT USE PROHIBITED
10-28 Designing and Implementing Stored Procedures
Key Points
In general, the reuse of query plans when a stored procedure is re-executed is a good thing. Sometimes
however, a stored procedure would benefit from an entirely different query execution plan for different
parameter values.
Parameter Sniffing
It has been mentioned that SQL Server attempts to reuse query execution plans from one execution of a
stored procedure to the next. While this is mostly helpful, imagine a procedure that takes a range of
names as parameters. If you ask for the rows from A to A, you might need a very different query plan to
the times when you ask for A to Z.
SQL Server provides a variety of ways to deal with this problem, often called a “parameter sniffing”
problem. Note that this only applies to parameters and not to variables within the batch. While the code
for these looks very similar, variable values are not “sniffed” at all and this can lead to poor execution
plans regardless.
WITH RECOMPILE
You can add a WITH RECOMPILE option when declaring a stored procedure. This causes the procedure to
be recompiled every time it is executed.
OPTIMIZE FOR
There is a query hint OPTION (OPTIMIZE FOR) that allows you to specify the value of a parameter that
should be assumed when compiling the procedure, regardless of the actual value of the parameter.
Question: How would you determine the value to assign in an OPTIMIZE FOR hint?
MCT USE ONLY. STUDENT USE PROHIBITED
10-30 Designing and Implementing Stored Procedures
Demonstration Steps
1. If Demonstration 1A was not performed:
• Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
• In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_10_PRJ\10776A_10_PRJ.ssmssln and
click Open.
• From the View menu, click Solution Explorer. 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.
Lesson 4
Controlling Execution Context
Stored procedures normally execute in the security context of the user calling the procedure. As long as a
chain of ownership extends from the stored procedure to the objects that are referenced, the user can
execute the procedure without the need for permissions on the underlying objects. Ownership chaining
issues with stored procedures are identical to those that were discussed for views in Module 9. Sometimes,
however, more precise control over the security context that the procedure is executing in is desired.
Objectives
After completing this lesson, you will be able to:
Key Points
The security context that a stored procedure executes in is referred to as its execution context. This
context is used to establish the identity against which permissions to execute statements or perform
actions are checked.
Execution Contexts
An execution context is represented by a login token and a user token. The tokens identify the primary
and secondary principals against which permissions are checked and the source used to authenticate the
token. A login connecting to an instance of SQL Server has one login token and one or more user tokens,
depending on the number of databases to which the account has access.
User Token: A user token is valid only for a specific database. It contains the primary and secondary
identities against which database-level permissions are checked. The primary identity is the database user
itself. The secondary identity includes permissions inherited from database roles. User tokens do not
contain server-role memberships and do not honor the server-level permissions granted to the identities
in the token including those that are granted to the server-level public role.
In the example shown in the slide, a WITH EXECUTE AS 'Pat' clause has been added to the definition of
the stored procedure. This causes the procedure to be executed with 'Pat' as the security context rather
than with the default security context supplied by the caller of the stored procedure.
Key Points
The EXECUTE AS clause sets the execution context of modules such as stored procedures. It is useful when
you need to override the default security context.
Explicit Impersonation
SQL Server supports the ability to impersonate another principal either explicitly by using the stand-alone
EXECUTE AS statement, or implicitly by using the EXECUTE AS clause on modules.
The stand-alone EXECUTE AS statement can be used to impersonate server-level principals, or logins, by
using the EXECUTE AS LOGIN statement. The stand-alone EXECUTE AS statement can also be used to
impersonate database level principals, or users, by using the EXECUTE AS USER statement.
To execute as another user, you must first have IMPERSONATE permission on that user. Any login in the
sysadmin role has IMPERSONATE permission on all users.
Implicit Impersonation
Implicit impersonations are performed through the WITH EXECUTE AS clause on modules and are used to
impersonate the specified user or login at the database or server level. This impersonation depends on
whether the module is a database-level module, such as a stored procedure or function, or a server-level
module, such as a server-level trigger.
When impersonating a principal by using the EXECUTE AS LOGIN statement, or within a server-scoped
module by using the EXECUTE AS clause, the scope of the impersonation is server-wide. This means that
after the context switch, any resource within the server that the impersonated login has permissions on
can be accessed.
However, when impersonating a principal by using the EXECUTE AS USER statement, or within a database-
scoped module by using the EXECUTE AS clause, the scope of impersonation is restricted to the database
by default. This means that references to objects outside the scope of the database will return an error.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-35
Key Points
You may wish to programmatically query the current security context details. These details are provided
by the sys.login_token and sys.user_token system views.
Demonstration Steps
1. If Demonstration 1A was not performed:
• Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
• In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_10_PRJ\10776A_10_PRJ.ssmssln and
click Open.
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
2. Open the 41 – Demonstration 4A.sql script file.
3. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-37
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
Lab Scenario
You need to create a set of stored procedures to support a new reporting application. The procedures will
be created within a new Reports schema.
MCT USE ONLY. STUDENT USE PROHIBITED
10-38 Designing and Implementing Stored Procedures
Supporting Documentation
Stored Procedure Reports.GetProductColors
Notes: Colors should not be returned more than once in the output. NULL values
should not be returned.
Input Parameters: @Color (same datatype as the Color column in the Marketing.Product table)
Output Columns: ProductID, ProductName, ListPrice (returned as a column named Price), Color,
Size and SizeUnitMeasureCode (returned as a column named UnitOfMeasure)
(from Marketing.Product)
Notes: The procedure should return products that have no Color if the parameter is
NULL.
(continued)
Notes: Colors should not be returned more than once in the output.
NULL values should not be returned.
Results: After this exercise, you should have created two new stored procedures. Tests should have
shown that they are working as expected.
MCT USE ONLY. STUDENT USE PROHIBITED
10-40
Results: After this exercise, you should have created a new stored procedure that takes parameters.
Tests should have shown that it is working as expected.
Results: After this exercise, you should have altered the stored procedures to execute as OWNER. Tests
should have shown that they are working as expected.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-41
Review Questions
1. What does the WITH RECOMPILE option do when used with a CREATE PROC statement?
2. What does the WITH RECOMPILE option do when used with an EXECUTE statement?
Best Practices
1. Use the EXECUTE AS clause to override the execution context of stored procedures that use dynamic
SQL, rather than granting permissions on the underlying tables to users.
2. Design procedures to perform individual tasks. Avoid designing procedures that perform a large
number of tasks, unless those tasks are performed by executing other stored procedures.
3. Keep consistent ownership of stored procedures, views, tables and other objects within databases.
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
11-1
Module 11
Merging Data and Passing Tables
Contents:
Lesson 1: Using the MERGE Statement 11-3
Lesson 2: Implementing TABLE Types 11-14
Lesson 3: Using TABLE Types As Parameters 11-22
Lab 11: Passing Tables and Merging Data 11-26
MCT USE ONLY. STUDENT USE PROHIBITED
11-2 Merging Data and Passing Tables
Module Overview
Each time a client application makes a call to a Microsoft® SQL Server® system, considerable delay is
encountered at the network layer. The basic delay is unrelated to the amount of data being passed. It
relates to the latency of the network. For this reason, it is important to minimize the number of times that
a client needs to call a server for a given amount of data that must be passed between them. Each call is
termed a “roundtrip”.
In this module you will review the techniques that provide the ability to process sets of data rather than
individual rows. You will then see how these techniques can be used in combination with TABLE
parameter types to minimize the number of required stored procedure calls in typical applications.
Objectives
After completing this lesson, you will be able to:
• Use the MERGE statement
Lesson 1
Using the MERGE Statement
A very common requirement when coding in T-SQL is the need to update a row if it exists but to insert
the row if it does not already exist. SQL Server 2008 introduced the MERGE statement that provides this
ability plus the ability to process entire sets of data rather than processing row by row or in several
separate set-based statements. In this lesson, you will investigate how to use the MERGE statement and
the most common options associated with it.
Objectives
After completing this lesson, you will be able to:
MERGE Statement
Key Points
The MERGE statement is most commonly used to insert data that does not already exist but to update the
data if it does exist. It can operate on entire sets of data rather than just on single rows and can perform
alternate actions such as deletes.
MERGE
It is a common requirement to need to update data if it already exists but to insert it if it does not already
exist. Some other database engines (not SQL Server) provide an UPSERT statement for this purpose. The
MERGE statement provided by SQL Server is a more capable replacement for such statements in other
database engines and is based on the ANSI SQL standard together with some Microsoft extensions to the
standard.
A typical situation where the need for the MERGE statement arises is in the population of data warehouses
from data in source transactional systems. For example, consider a data warehouse holding details of a
customer. When a customer row is received from the transactional system, it needs to be inserted into the
data warehouse. When later updates to the customer are made, the data warehouse would then need to
be updated. Note that data warehouses often implement more complex versioning of rows but these
techniques are beyond the scope of this course.
Atomicity
Where statements in other languages typically operate on single rows, the MERGE statement in SQL
Server can operate on entire sets of data in a single statement execution. It is important to realize that the
MERGE statement functions as an atomic operation in that all inserts, updates or deletes occur or none
occur.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-5
The source table provides the rows that need to be matched to the rows in the target table. You can think
of the source table as the incoming data. It is specified in a USING clause. The source table does not have
to be an actual table but can be other types of expressions that return a table such as:
• A view
WHEN MATCHED
Key Points
The WHEN MATCHED clause defines the action that needs to be taken when a row in the source is
matched to a row in the target.
WHEN MATCHED
The ON clause is used to match source rows to target rows. The WHEN MATCHED clause specifies the
action that needs to occur when a source row matches a target row. In most cases, this will involve an
UPDATE statement but it could involve a DELETE statement.
In the example shown on the slide, rows in the EmployeeUpdate table are being matched to rows in the
Employee table based upon the EmployeeID. When a source row matches a target row, the FullName and
EmploymentStatus columns in the target table are updated with the values of those columns in the
source.
Note that only the target table can be updated. If an attempt is made to modify any other table, a syntax
error is returned.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-7
Multiple Clauses
It is also possible to include two WHEN MATCHED clauses as shown in the following code block:
No more than two WHEN MATCHED clauses can be present. When two clauses are used, the first clause
must have an AND condition. If the source row matches the target and also satisfies the AND condition,
then the action specified in the first WHEN MATCHED clause is performed. Otherwise, if the source row
matches the target but does not satisfy the AND condition, the condition in the second WHEN MATCHED
clause is evaluated instead.
When two WHEN MATCHED clauses are present, one action must specify an UPDATE and the other action
must specify a DELETE.
Question: What is different about the UPDATE statement in the example shown, compared to a
normal UPDATE statement?
MCT USE ONLY. STUDENT USE PROHIBITED
11-8 Merging Data and Passing Tables
Key Points
The WHEN NOT MATCHED BY TARGET clause specifies the action that needs to be taken when a row in
the source cannot be matched to a row in the target.
In the example shown in the slide, when a row from the EmployeeUpdate table cannot be found in the
Employee table, a new employee row would be added into the Employee table.
With a standard INSERT statement in T-SQL, the inclusion of a column list is considered a best practice
and avoids issues related to changes to the underlying table such as the reordering of columns or the
addition of new columns. The same recommendation applies to an INSERT action within a MERGE
statement. While a column list is optional, best practice suggests including one.
Syntax
The words BY TARGET are optional and are often omitted. The clause is then just written as WHEN NOT
MATCHED. Note again that no table name is included in the action statement (INSERT statement) as
modifications may only be made to the target table.
The WHEN NOT MATCHED BY TARGET clause is part of the ANSI SQL standard.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-9
Key Points
The WHEN NOT MATCHED BY SOURCE statement is used to specify an action to be taken for rows in the
target that were not matched by rows from the source.
The MERGE statement can have at most two WHEN NOT MATCHED BY SOURCE clauses. If two clauses are
specified, then the first clause must be accompanied by an AND search condition clause. For any given
row, the second WHEN NOT MATCHED BY SOURCE clause is only applied if the first is not. If there are
two WHEN NOT MATCHED BY SOURCE clauses, then one clause must specify an UPDATE action and one
must specify a DELETE action. Only columns from the target table can be referenced in the search
condition clause.
Note the format of the DELETE statement in the example on the slide. At first glance, it might seem quite
odd as it has no table or predicate specified. In this example, all rows in the Employee table that were not
matched by an incoming source row from the EmployeeUpdate table would be deleted.
Question: What would the DELETE statement look like if it only deleted rows where the date in a
column called LastModifed were older than a year?
MCT USE ONLY. STUDENT USE PROHIBITED
11-10 Merging Data and Passing Tables
Key Points
The OUTPUT clause was added in SQL Server 2005 and allows the return of a set of rows when performing
data modifications. In 2005, this applied to INSERT, DELETE and UPDATE. In SQL Server 2008 and later,
this clause can also be used with the MERGE statement.
OUTPUT Clause
The OUTPUT clause was a useful addition to the INSERT, UPDATE and DELETE statements in SQL Server
2005. For example, consider the following code:
In this example, employee rows are deleted when the rows holding their details have not been modified
within the last ten years. As part of this modification, a set of rows is returned that provides details of the
BusinessEntityID and NationalIDNumber for each row deleted.
As well as returning rows to the client application, the OUTPUT clause can include an INTO sub-clause
that causes the rows to be inserted into another existing table instead. Consider the following example:
In this example, details of the employees being deleted are inserted into the Audit.EmployeeDelete table
instead of being returned to the client.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-11
Because a single MERGE statement can perform INSERT, UPDATE and DELETE actions, it can be useful to
know which action was performed for each row returned by the OUTPUT clause. To make this possible,
the OUTPUT clause also supports a $action virtual column that returns details of the action performed on
each row. It returns the words “INSERT”, “UPDATE” or “DELETE”.
Composable SQL
In SQL Server 2008 and later, it is now possible to consume the rowset returned by the OUTPUT clause
more directly. Code whose output can be consumed by other code is referred to as consumable code. The
rowset cannot be used as a general purpose table source but can be used as a table source for an INSERT
SELECT statement. Consider the following example:
In this example, the OUTPUT clause is being used with the MERGE statement. A row would be returned for
each row either updated or deleted. However, you wish to only audit the deletion. You can treat the
MERGE statement with an OUTPUT clause as a table source for an INSERT SELECT statement. The enclosed
statement must be given an alias. In this case, the alias “Mods” has been assigned.
The power of being able to SELECT from a MERGE statement is that you can then apply a WHERE clause.
In this example, only the DELETE actions have been selected.
Note that from SQL Server 2008 onwards, this level of query composability also applies to the OUTPUT
clause when used in standard T-SQL INSERT, UPDATE and DELETE statements.
Key Points
The actions performed by a MERGE statement are not identical to those that would be performed by
separate INSERT, UPDATE or DELETE statements.
Determinism
When an UPDATE statement is executed with a join, if more than one source row matches a target row or
the other way around, no error is thrown. This is not permitted for an UPDATE action performed within a
MERGE statement. An UPDATE can allow a single source row to update multiple target rows but if more
than one source row updates a single target row, an error occurs and all actions performed by the MERGE
statement are rolled back.
Performance of MERGE
The MERGE statement will often outperform code constructed from separate INSERT, UPDATE and
DELETE statements and conditional logic. In particular, the MERGE statement only ever makes a single
pass through the data in the target table.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-13
Demonstration Steps
1. Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_11_PRJ\10776A_11_PRJ.ssmssln and click Open.
3. From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file from
within Solution Explorer.
5. Follow the instructions contained within the comments of the script file.
Lesson 2
Implementing TABLE Types
It was mentioned earlier that reducing the number of calls between client applications and SQL Server is
important. The aim is to minimize the amount of time lost through network delays and latency.
SQL Server 2000 introduced the TABLE data type for use as variables. SQL Server 2008 introduced the
ability to declare these as permanent (or temporary) data types and to use them as parameters. The use of
TABLE valued parameters can significantly reduce the number of round trips needed between client
application code and SQL Server.
Objectives
After completing this lesson, you will be able to:
• Explain the need to reduce round-trip overhead
Key Points
In many applications, the time taken for commands to be sent to the server and for responses to be
received can be substantial. It can often be longer than the time to execute the SQL command at the
server. That is why it is desirable to minimize the number of times this happens in an operation.
Consider what is involved in inserting a new customer order into a SQL Server database. You typically
need to do the following:
• Start a transaction
• Save the order header
• Save the first order detail line
• Save the second order detail line
• Save the third order detail line
• Commit the transaction
This means that performing a single action results in six separate round trips to the server.
Transaction Duration
A golden rule when designing systems to maximize concurrency is to never hold a transaction open for
longer than required. In the previous example, the transaction is being held open for the time to insert
the order header and detail lines. While the transaction needs to be held open for this time, its duration is
being artificially increased by the time taken to make all the round trips to the server. This is not desirable.
Question: How could the number of round trips being made to the server be reduced?
MCT USE ONLY. STUDENT USE PROHIBITED
11-16 Merging Data and Passing Tables
Key Points
One method for reducing the number of round trips from a client application to SQL Server is to pass lists
of values in each trip.
Previous Options
Prior to SQL Server 2008, the available options for passing lists of values within a single procedure call
were very limited. The most commonly used method was to use delimited lists. Mostly these were
implemented as comma-delimited lists but other delimiters (eg: pipe) were used.
When delimited lists were used, the entire set of values was sent as a string. There were issues with
doing this:
• No control was able to be exerted over the data type being passed. A string could be passed to code
expecting a number.
• The structure was loose. For example, one string might contain five columns and another might
contain six.
Passing XML
Another option for passing lists of values was to use XML. This became more common with SQL Server
2005 when the XML data type was introduced. Prior to SQL Server 2005, developers would also
sometimes pass XML values as strings but they then needed to write very complex parsing logic.
With the introduction of the XML data type, the parsing became easier but not trivial. Processing the
received XML is also non-trivial and some processing methods (such as OPENXML) had memory
implications, while others (such as the nodes() method) had query optimization implications. In Modules
17 and 18 you will learn more about the use of XML in SQL Server.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-17
Demonstration Steps
1. If Demonstration 1A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
Question: What are the basic problems with using delimited lists for parameters?
MCT USE ONLY. STUDENT USE PROHIBITED
11-18 Merging Data and Passing Tables
Key Points
SQL Server 2008 introduced the ability to create user TABLE data types and record them in the system
catalog. These types are very useful as they can be used for both variables and for parameters.
In SQL Server 2000, it was possible to declare a variable of type TABLE. You needed to define the schema
of the table when declaring the variable such as in the following code:
In this example, a variable called @BalanceList is defined as being a table. The schema of the table and
the variable, only last for the duration of the batch in which the variable is defined.
SQL Server 2008 introduced the ability to create user-defined table data type definitions. You can create
table data types that can be used both for the data type of variables but also for the data type of
parameters. In the example shown on the slide, CustomerBalance is declared as a new data type. You can
declare a variable as being of CustomerBalance data type as follows:
A key advantage of table data types is that you can pass complex structures inside a table more easily
than you could in alternatives such as comma-delimited lists. You can have multiple rows each of two or
more columns and can be sure of the data types that will be stored.
Note that there is no ALTER TYPE statement that can be used to modify the TABLE type definition. Types
must be dropped and then recreated when they need to be altered.
MCT USE ONLY. STUDENT USE PROHIBITED
11-20 Merging Data and Passing Tables
Key Points
SQL Server 2008 also introduced the concept of row constructors and multi-row INSERT statements. These
are useful when working with TABLE data types as well as when working with database tables.
In the example shown on the slide, a variable named @Balance of type dbo.CustomerBalance has been
declared. That data type was the table data type that was defined in the example from the previous topic.
Three rows have then been inserted into the table variable.
Note that a multi-row INSERT that inserts 3 rows is quite different from 3 separate INSERT statements. It is
an atomic operation involving 3 rows where all inserts occur or none occur. Note also that multi-row
INSERT statements cannot include more than 1000 rows per statement and that multi-row INSERTS also
help reduce the number of roundtrips from a client application to a server.
Question: What would improve the INSERT query shown in the slide example?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-21
Demonstration Steps
1. If Demonstration 1A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
Question: Can other users make use of the TABLE type that you create?
MCT USE ONLY. STUDENT USE PROHIBITED
11-22 Merging Data and Passing Tables
Lesson 3
Using TABLE Types As Parameters
In the previous lesson you saw how to declare TABLE data types and how to declare variables of those
types. Another potential use for the TABLE data type is in the declaration of parameters, particularly for
use with stored procedures but also able to be used with user-defined functions.
In this lesson, you will see how to use TABLE input parameters in conjunction with stored procedures and
see how this solves the round trip problems identified in lesson 1. You will also see how to call a stored
procedure when passing a table valued parameter.
Objectives
After completing this lesson, you will be able to:
• Describe the use of TABLE input parameters for stored procedures
Key Points
In addition to being used for declaring variables, user-defined table data types can be used as parameter
data types for stored procedures and functions. (User-defined functions will be discussed in Module 12.)
In the example shown on the slide, a data type called SalesDetails is being created to hold the detail lines
for a customer sale. A stored procedure is then being created that takes sales header details as standard
relational parameters and also takes the entire list of sales details rows as a single parameter. This allows
for the creation of a stored procedure that would process an entire sale in a single call.
What is more interesting though is that you could pass multiple order headers and their corresponding
order detail rows in a single call. This means that the procedure could now save one or more orders with
all their detail rows in a single round-trip to the server.
Question: What would you have to do to be able to pass multiple sales and their detail lines in a
single call?
MCT USE ONLY. STUDENT USE PROHIBITED
11-24 Merging Data and Passing Tables
Key Points
In the previous topic, you saw how to declare a stored procedure that uses a table-valued parameter. The
final step in using such a procedure is to then pass a table parameter in the EXEC statement.
First, you declare a table variable with the same user-defined table data type that was used when
declaring the stored procedure.
Next, you populate that variable. Row constructors are ideal for populating the table variables that will be
passed in an EXEC call. In the example shown on the slide, three product detail rows are being inserted
into the @SalesDetails variable.
Finally, the stored procedure is called via an EXEC statement and the detail rows are passed as a single
parameter. You will see this in detail in the upcoming demonstration.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-25
Demonstration Steps
1. If Demonstration 1A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
Question: What is the purpose of the SCOPE_IDENTITY() function shown in the demonstration?
MCT USE ONLY. STUDENT USE PROHIBITED
11-26 Merging Data and Passing 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:
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click
SQL Server Management Studio.
3. In Connect to Server window, type Proseware in the Server name text box.
4. In the Authentication drop-down list box, select Windows Authentication and click Connect.
7. From the View menu, click Solution Explorer. In Solution Explorer, double-click the query
00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
In earlier versions of SQL Server, passing lists of values to stored procedures was a challenge. SQL Server
2008 introduced the TABLE type and table-valued parameters. In this lab, you will create a replacement
stored procedure Reports.GetProductsByColorList_Test that uses a table-valued parameter to replace an
existing stored procedure Reports.GetProductsByColorList that was based on passing a comma-delimited
list of values.
If time permits, you will then create a new procedure that processes complete rows of data and performs
updates using the MERGE statement.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-27
Supporting Documentation
Requirements
Output Rows: For each row, return one column called Action that contains INSERT or
UPDATE and another column with the SalespersonID.
Results: After this exercise, you should have created a new TABLE type.
MCT USE ONLY. STUDENT USE PROHIBITED
11-28 Merging Data and Passing Tables
Results: After this exercise, you should have created a new stored procedure that uses the TABLE type
for its parameter.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-29
Challenge Exercise 3: Use a TABLE Type with MERGE (Only if time permits)
Scenario
In this exercise, you will create a new stored procedure that takes a table-valued parameter and uses the
MERGE statement to update a table in the marketing system. The procedure should allow for the creation
or update of salespeople held in the Marketing.Salesperson table.
Results: After this exercise, you should have created a new stored procedure that takes a table-valued
parameter and uses the MERGE statement to update a table.
MCT USE ONLY. STUDENT USE PROHIBITED
11-30 Merging Data and Passing Tables
Review Questions
1. What is the difference between SOURCE NOT MATCHED and TARGET NOT MATCHED in a MERGE
statement?
Best Practices
1. Use multi-row inserts when the rows being inserted are related in some way, for example, the detail
rows of an invoice.
Module 12
Designing and Implementing User-Defined Functions
Contents:
Lesson 1: Overview of Functions 12-3
Lesson 2: Designing and Implementing Scalar Functions 12-7
Lesson 3: Designing and Implementing Table-valued Functions 12-13
Lesson 4: Considerations for Implementing Functions 12-18
Lesson 5: Alternatives to Functions 12-25
Lab 12: Designing and Implementing User-defined Functions 12-28
MCT USE ONLY. STUDENT USE PROHIBITED
12-2 Designing and Implementing User-Defined Functions
Module Overview
Functions are routines that are used to encapsulate frequently performed logic. Rather than having to
repeat all the function logic, any code that must perform the logic can call the function.
In this lesson, you will learn to design and implement user-defined functions that enforce business rules or
data consistency, and to modify and maintain existing functions written by other developers.
Objectives
After completing this lesson, you will be able to:
Lesson 1
Overview of Functions
Functions are routines made up of one or more Transact-SQL statements that can be used to encapsulate
code for reuse. A function takes zero or more input parameters and returns either a scalar value or a table.
Functions do not support output parameters, but do return results, either a single value or a table.
Objectives
After completing this lesson, you will be able to:
Types of Functions
Key Points
Most high-level programming languages offer functions as blocks of code that are called by name and
which can process input parameters. ®Microsoft SQL Server® has several types of functions: scalar
functions, table-valued functions, and system functions. Table-valued functions can be created in two
ways: inline functions and multi-statement functions.
Scalar Functions
Scalar functions return a single data value of the type defined in a RETURNS clause. An example of a scalar
function would be a function that extracts the protocol from a URL. From the string
“http://www.microsoft.com”, the function would return the string “http”.
For example, if a table holds details of sales for an entire country, individual views could be created to
return details of sales for particular states within the country. An inline table-valued function could be
written that takes the state code or ID as a parameter and returns all the details of sales for the state that
match the parameter. In this way, only a single function would be needed to provide details for all states,
rather than separate views for each state.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-5
System Functions
System functions are built-in functions provided by SQL Server to help you perform a variety of
operations. They cannot be modified. System functions are described in the next topic.
System Functions
Key Points
SQL Server has a wide variety of built-in functions that you can use in queries to return data or to perform
operations on data.
System Functions
Most of the functions are scalar functions and provide the functionality that is commonly provided by
functions in other high-level languages such as operations on data types (including strings and dates and
times) and conversions between data types.
A library of mathematical and cryptographic functions is provided by SQL Server. Other functions provide
details of the configuration of the system and its security.
Aggregates such as MIN, MAX, AVG, SUM, and COUNT perform calculations across groups of rows. Many
of these functions automatically ignore NULL rows.
Ranking functions such as ROW_NUMBER, RANK, DENSE RANK, and NTILE perform windowing operations
on rows of data.
Question: Have you used any of the functions apart from data type and date time when writing
code?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-7
Lesson 2
Designing and Implementing Scalar Functions
You have seen that functions are routines made up of one or more Transact-SQL statements that can be
used to encapsulate code for reuse, and that functions can take zero or more input parameters and return
either scalar values or tables.
This lesson provides an overview of scalar functions and explains why and how you use them, in addition
to the syntax for creating them.
Objectives
After completing this lesson, you will be able to:
Key Points
You use scalar functions to return information from a database. A scalar function returns a single data
value of the type defined in a RETURNS clause.
Scalar Functions
Unlike the definition of a stored procedure, where the use of a BEGIN…END that wraps the body of the
stored procedure is optional, the body of the function must be defined in a BEGIN…END block. The
function body contains the series of Transact-SQL statements that return the value.
Note that the body of the function comprises a single RETURN statement that is wrapped in a
BEGIN…END block. This function can be used as an expression wherever a single value could be used:
SELECT dbo.ExtractProtocolFromURL(N'http://www.microsoft.com');
IF (dbo.ExtractProtocolFromURL(@URL) = N'http')
...
Scalar functions can also be implemented in managed code. Managed code will be discussed in Module
16. The allowable return values for scalar functions differ between functions that are defined in T-SQL and
functions that are defined using managed code.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-9
Key Points
User-defined functions are created using the CREATE FUNCTION statement, modified using the ALTER
FUNCTION statement, and removed using the DROP FUNCTION statement. Even though the body of the
function (apart from inline functions) must be wrapped in a BEGIN…END block, the CREATE FUNCTION
must be the only statement in the batch.
Guidelines
Consider the following guidelines when you create scalar user-defined functions:
• Make sure that you use two-part naming for the function and for all database objects referenced by
the function.
• Avoid Transact-SQL errors that cause a statement to be canceled and continue with the next
statement in the module (such as within triggers or stored procedures) because they are treated
differently inside a function. In functions, such errors cause the execution of the function to stop.
Side-effects
A function that modifies the underlying database is considered to have “side-effects”. In SQL Server,
functions are not permitted to have side-effects. You cannot change data in a database within a function,
may not call a stored procedure and may not execute dynamic SQL code.
MCT USE ONLY. STUDENT USE PROHIBITED
12-10 Designing and Implementing User-Defined Functions
Key Points
Both built-in and user-defined functions fall into one of two categories: deterministic and
nondeterministic. This distinction is important as it determines where a function can be used. For example,
a nondeterministic function cannot be used in the definition of a calculated column.
Deterministic Functions
A deterministic function is one that will always return the same result when provided with the same set of
input values and for the same database state. Consider the following function definition:
Every time the function is called with the same two integer values, it would return exactly the same result.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-11
Non-deterministic Functions
A non-deterministic function is one that may return different results for the same set of input values each
time it is called, even if the database remains in the same state.
Each time the function is called, it would return a different value, even though no input parameters are
supplied.
Demonstration Setup
1. Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_12_PRJ\10776A_12_PRJ.ssmssln and click Open.
3. From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file from
within Solution Explorer.
4. Open the 21 – Demonstration 2A.sql script file.
5. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-13
Lesson 3
Designing and Implementing Table-valued Functions
In this lesson you will learn how to work with functions that return tables instead of single values. There
are two types of table-valued functions (TVFs): inline and multi-statement. Both types of TVF will be
covered in this lesson.
The ability to return a table of data is important as it allows a function to be used as a source of rows in
place of a table in a T-SQL statement. In many cases, this can avoid the need to store data temporary
tables.
Objectives
After completing this lesson, you will be able to:
• Describe table-valued functions
Key Points
Unlike scalar functions, TVFs return a table that can contain many rows of data, each with many columns.
Table-valued Functions
There are two ways to create TVFs. Inline TVFs return an output table defined by a RETURN statement that
is comprised of a single SELECT statement. If the logic of the function is too complex to include in a single
SELECT statement, the function needs to be implemented as a multi-statement TVF.
Multi-statement TVFs construct a table within the body of the function and then return the table. They
also need to define the schema of the table to be returned.
Key Points
You can use inline functions to achieve the functionality of parameterized views. One of the limitations
of a view is that you are not allowed to include a user-provided parameter within the view when you
create it.
Inline TVFs
In the syntax example shown on the slide, note that the return type is TABLE. The definition of the
columns of the table is not shown. You do not explicitly define the schema of the returned table. The
output table schema is derived from the SELECT statement that you provide within the RETURN
statement. Every column returned by the SELECT statement should also have a distinct name.
For inline functions, the body of the function is not enclosed in a BEGIN…END block. A syntax error
occurs if you attempt to use them. The CREATE FUNCTION statement still needs to be the only statement
in the batch.
Question: TVFs return rows of data as tables. You have learned that tables do not have a predefined
order. Why does the example function in the slide include an ORDER BY clause?
MCT USE ONLY. STUDENT USE PROHIBITED
12-16 Designing and Implementing User-Defined Functions
Key Points
A multi-statement table-valued function allows for more complexity in how the table to be returned is
constructed. You can use user-defined functions that return a table to replace views. This is very useful
when the logic required for constructing the return table is more complex than would be possible within
the definition of a view.
Multi-statement TVFs
A table-valued function (like a stored procedure) can use complex logic and multiple Transact-SQL
statements to build a table.
In the example on the slide, a function is created that returns a table of dates. For each row, two columns
are returned: the position of the date within the range of dates, and the calculated date. As the system
does not already include a table of dates, a loop needs to be constructed to calculate the required range
of dates. This cannot be implemented in a single SELECT statement unless another object such as a table
of numbers, is already present in the database. In each iteration of the loop, an INSERT is performed into
the table that is later returned.
In the same way that you use a view, you can use a table-valued function in the FROM clause of a
Transact-SQL statement.
Question: Can you think of a situation where you would need to use a Multi-statement Table-valued
Function rather than an Inline Table-valued Function?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-17
Demonstration Steps
1. If Demonstration 2A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
Question: What are some commonly used SQL Scalar functions that you can think of?
MCT USE ONLY. STUDENT USE PROHIBITED
12-18 Designing and Implementing User-Defined Functions
Lesson 4
Considerations for Implementing Functions
While the ability to create functions in T-SQL is very important, there are some key considerations that
need to be made when creating functions. In particular, it is important to avoid negative performance
impacts through inappropriate use of functions. Performance problems due to such inappropriate usage
are very common. This lesson provides guidelines for the implementation of functions and describes how
to control their security context.
Objectives
After completing this lesson, you will be able to:
Key Points
The code for views is incorporated directly into the code for the query that accesses the view. This is not
the case for scalar functions.
In many cases, extracting the code from the function definition and incorporating it directly into the
query will resolve the performance issue. You will see an example of this in the next lab.
MCT USE ONLY. STUDENT USE PROHIBITED
12-20 Designing and Implementing User-Defined Functions
Key Points
Whether or not the code for a TVF is incorporated into the query that uses the function depends upon the
type of table-valued function. Inline TVFs are directly incorporated into the code of the query that uses
them.
The CROSS APPLY operator is used to call a table-valued function for each row in the left-hand table
within the query. Designs that require the calling of a TVF for every row in a table can lead to significant
performance overhead. You should examine the design to see if there is a way to avoid the need to call
the function for each row.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-21
Key Points
Execution context is determined by the user or login connected to the session, or executing (calling) a
module.
Execution context establishes the identity against which permissions are checked. The user or login calling
a module, such as a stored procedure or function, usually determines execution context.
When you use the EXECUTE AS clause to change the execution context so that a code module executes as
a user other than the caller, the code is said to “impersonate” the alternative user.
Before you can create a function that executes as another user, you need to have IMPERSONATE
permission on that user, or be part of the dbo role.
MCT USE ONLY. STUDENT USE PROHIBITED
12-22 Designing and Implementing User-Defined Functions
Key Points
The EXECUTE AS clause sets the execution context of a session. You can use the EXECUTE AS clause in a
stored procedure or function to set the identity used as the execution context for the stored procedure or
function.
EXECUTE AS allows you to create procedures that execute code that the user executing the procedure is
not permitted to execute, without the need for concerns regarding broken ownership chains or dynamic
SQL execution.
SQL Server supports the ability to impersonate another principal either explicitly by using the stand-alone
EXECUTE AS statement, or implicitly by using the EXECUTE AS clause on modules. The stand-alone
EXECUTE AS statement can be used to impersonate server-level principals, or logins, by using the
EXECUTE AS LOGIN statement. The stand-alone EXECUTE AS statement can also be used to impersonate
database level principals, or users, by using the EXECUTE AS USER statement.
Implicit impersonations that are performed through the EXECUTE AS clause on modules impersonate the
specified user or login at the database or server level. This impersonation depends on whether the module
is a database-level module, such as a stored procedure or function, or a server-level module, such as a
server-level trigger.
When impersonating a principal by using the EXECUTE AS LOGIN statement, or within a server-scoped
module by using the EXECUTE AS clause, the scope of the impersonation is server-wide. This means that
after the context switch, any resource within the server that the impersonated login has permissions on
can be accessed.
However, when impersonating a principal by using the EXECUTE AS USER statement, or within a database-
scoped module by using the EXECUTE AS clause, the scope of impersonation is restricted to the database
by default. This means that references to objects outside the scope of the database will return an error.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-23
Key Points
Consider the following guidelines when you create user-defined functions:
• The performance of inline functions is, in many cases, much higher than the performance of multi-
statement functions. Wherever possible, try to implement functions as inline functions.
• Avoid building large general purpose functions. Keep functions relatively small and targeted at a
specific purpose. This will avoid code complexity but will also increase the opportunities for reusing
the functions.
• Use two-part naming to qualify the name of any database objects referred to within the function and
also use two-part naming when choosing the name of the function.
• Consider the impact of using functions in combination with indexes. In particular, note that a WHERE
clause that uses a predicate like:
• Avoid statements that will raise T-SQL errors as exception handling is not allowed within functions.
MCT USE ONLY. STUDENT USE PROHIBITED
12-24 Designing and Implementing User-Defined Functions
Demonstration Steps
1. If Demonstration 2A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-25
Lesson 5
Alternatives to Functions
Functions are only one option for implementing code. This lesson explores situations where other
solutions may or may not be appropriate and helps you make decisions about which solution to use.
Objectives
After completing this lesson, you will be able to:
Key Points
Table-valued functions and stored procedures can often be used to achieve similar outcomes. It is
important to realize that not all client applications can call both. This means that they cannot necessarily
be used interchangeably. There are also pros and cons of each approach.
While it is possible to access the output rows of a stored procedure with an INSERT EXEC statement, it is
easier to consume the output of a function in code than the output of a stored procedure.
Stored procedures can modify data in database tables. Functions cannot modify data in database tables.
Functions that include such “side-effects” are not permitted. Functions can have significant performance
impacts when called for each row in a query, such as occurs when a Table-valued function is called with a
CROSS APPLY or OUTER APPLY statement.
Stored procedures can execute dynamic SQL statements. Functions are not permitted to execute dynamic
SQL statements.
Stored procedures can include detailed exception handling. Functions cannot contain exception handling.
Stored procedures can return multiple resultsets from a single stored procedure call. Table-valued
functions are able to return a single rowset from a function call. There is no mechanism to permit the
return of multiple rowsets from a single function call.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-27
Key Points
TVFs can provide similar outcomes to views.
Views and parameter-less TVFs are usually able to be consumed by most client application that can access
tables. Not all such applications can pass parameters to a table-valued function.
Views and inline TVFs can be updatable. Multi-statement TVFs are not updatable.
Views can have INSTEAD OF triggers associated with them. This is mostly used to provide for updatable
views based on multiple base tables.
Views and inline table-valued functions are incorporated into surrounding queries. Multi-statement table-
valued functions are not incorporated into surrounding queries and often lead to performance issues
when used inappropriately.
MCT USE ONLY. STUDENT USE PROHIBITED
12-28 Designing and Implementing User-Defined Functions
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. Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click
SQL Server Management Studio.
4. In Connect to Server window, type Proseware in the Server name text box.
5. In the Authentication drop-down list box, select Windows Authentication and click Connect.
8. From the View menu, click Solution Explorer. In Solution Explorer, double-click the query
00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
The existing marketing application includes some functions. Your manager has requested your assistance
in creating a new function for formatting phone numbers. She also needs you to modify an existing
function to improve its usability.
Finally, if you have time, she would also like you to explore a performance-related problem with another
existing function.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-29
Supporting Documentation
Function Specifications: Phone Number
Function Name: FormatPhoneNumber (created in the dbo schema)
Input Parameter: PhoneNumberToFormat nvarchar(16)
Return Value: nvarchar(16)
Rules to apply in formatting:
• Any phone number beginning with the international dialing code (ie: a + sign), should be left
unformatted.
• Phone numbers that contain 10 digits should be formatted as: (XXX) XXX-XXXX
Results: After this exercise, you should have created a new FormatPhoneNumber function within the
dbo schema.
f Task 4: Test the function with an alternate delimiter such as the pipe | character
• Test the dbo.IntegerListToTable function and pass in an alternate delimiter such as the pipe |
character.
Results: After this exercise, you should have created a new IntegerListToTable function within a dbo
schema.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-31
f Task 3: Use SET STATISTICS TIME ON to compare the performance of the new and
old queries
• Turn SET STATISTICS TIME ON.
• Use the times returned to test how your new query compares with the original.
Results: After this exercise, you should have created an alternate query for the poorly-performing
query.
MCT USE ONLY. STUDENT USE PROHIBITED
12-32 Designing and Implementing User-Defined Functions
Review Questions
1. When using the EXECUTE AS clause, what privileges should the login or user being impersonated
have?
2. When using the EXECUTE AS clause, what privileges should the login or user creating the code have?
Best Practices
1. Avoid calling multi-statement TVFs for each row of a query. In many cases, you can dramatically
improve performance by extracting the code from the query into the surrounding query.
2. Use the WITH EXECUTE AS clause to override the security context of code that needs to perform
actions that the user that is executing the code, does not have.
MCT USE ONLY. STUDENT USE PROHIBITED
13-1
Module 13
Creating Highly Concurrent SQL Server® 2012 Applications
Contents:
Lesson 1: Introduction to Transactions 13-3
Lesson 2: Introduction to Locks 13-17
Lesson 3: Management of Locking 13-28
Lesson 4: Transaction Isolation Levels 13-38
Lab 13: Creating Highly Concurrent SQL Server Applications 13-44
MCT USE ONLY. STUDENT USE PROHIBITED
13-2 Creating Highly Concurrent SQL Server 2012 Applications
Module Overview
It is the responsibility of an enterprise database system to provide mechanisms that ensure the physical
integrity of each transaction. A transaction is a sequence of operations performed as a single logical unit
of work, and Microsoft® SQL Server® provides locking facilities that preserve transaction isolation. In this
module, you will learn how to manage transactions and locks.
Database systems struggle with the need to balance consistency and concurrency. There is often a direct
trade-off between these two aims. The challenge is to use the lowest concurrency impact possible while
still maintaining sufficient consistency.
This module explains how to use transactions and the SQL Server locking mechanisms to meet the
performance and data integrity requirements of your applications.
Another aim of database management systems is to provide each user with the illusion wherever possible
that they are the only user on the system. Transaction isolation levels are critical to minimizing the impact
of one user on another. In this module you will also investigate transaction isolation levels.
Objectives
After completing this module, you will be able to:
Lesson 1
Introduction to Transactions
A core capability provided by relational database management systems such as SQL Server is to provide
the ability to group a set of changes that need to be made and to ensure that the entire set of changes
occurs or that none occur. Transactions are how this requirement is met within SQL Server.
Objectives
After completing this lesson, you will be able to:
• Explain what transactions are
Key Points
A transaction is a sequence of steps that perform a logical unit of work. They must exhibit four properties
that are collectively known as ACID. Transactions ensure that multiple data modifications are processed as
a unit. For example, a banking transaction might credit one account and debit another. Both steps must
be completed together or not at all. SQL Server supports transaction processing to manage multiple
transactions.
Atomicity
Atomicity means that either all the steps in the transaction must succeed or none of them should be
performed. For example, when money is transferred between two bank accounts, both the debit and
credit actions must occur or none should occur.
Consistency
Consistency ensures that when the transaction is complete, data must be in a consistent state. A consistent
state is one where the data conforms to the business rules related to the data. Inconsistent data violates
one or more business rules. In SQL Server, the database has to be in a consistent state after each
statement within a transaction and not only at the end of the transaction.
Isolation
Isolation defines that changes made by a transaction must be isolated from other concurrent transactions.
Durability
Durability defines that when the transaction is complete, the changes must be made permanent in the
database and must survive even system failures.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-5
Transaction Log
Every transaction is recorded in a transaction log to maintain database consistency and to aid in
transaction recovery. When changes are made to data in SQL Server, the changes are written to the
transaction log on the disk first and the database pages are written to the database at some later time. If
any part of the transaction fails, all of the changes made so far are rolled back to leave the database in its
original state. This system ensures that updates are complete and recoverable.
Transactions use locking to prevent other users from changing or reading data in a transaction that has
not completed. Locking is required in online transaction processing (OLTP) for multi-user systems.
Question: Can you think of database operations in your organization where database transactions
are especially critical?
MCT USE ONLY. STUDENT USE PROHIBITED
13-6 Creating Highly Concurrent SQL Server 2012 Applications
Key Points
Autocommit mode is the default transaction management mode of the SQL Server Database Engine.
Every Transact-SQL statement is committed or rolled back when it completes. If a statement completes
successfully, it is committed; if it encounters any error, it is rolled back.
Autocommit Mode
A connection to an instance of the Database Engine operates in autocommit mode whenever this default
mode has not been overridden by either explicit or implicit transactions. Autocommit mode is also the
default mode for ADO, OLE DB, ODBC, and DB-Library.
A connection to an instance of the Database Engine operates in autocommit mode until a BEGIN
TRANSACTION statement starts an explicit transaction, or implicit transaction mode is set on. When the
explicit transaction is committed or rolled back, or when implicit transaction mode is turned off, the
connection returns to autocommit mode.
If a run-time statement error (such as a constraint violation) occurs in a batch, the default behavior in the
Database Engine is to roll back only the statement that generated the error. You can change this behavior
using the SET XACT_ABORT statement. After SET XACT_ABORT ON is executed, any run-time statement
error causes the batch to quit and if you are currently in a transaction, that would cause an automatic
rollback of the current transaction.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-7
Compile Errors
Compile errors, such as syntax errors, are not affected by SET XACT_ABORT. When working in autocommit
mode, compile time errors can cause more than one Transact-SQL statement to fail. In this mode, a batch
of statements is compiled as a unit and if a compile error is found, nothing in the batch is compiled or
executed. The following example shows how this might happen:
USE AdventureWorks2008;
GO
CREATE TABLE NewTable (Id INT PRIMARY KEY, Info CHAR(3));
GO
INSERT INTO NewTable VALUES (1, 'aaa');
INSERT INTO NewTable VALUES (2, 'bbb');
INSERT INTO NewTable VALUSE (3, 'ccc'); -- Syntax error.
GO
SELECT * FROM NewTable; -- Returns no rows.
GO
Because there is a typographical error in the third INSERT statement, the batch cannot compile, and so
none of the three INSERT statements run and execution continues with the SELECT statement in the next
batch.
XACT_ABORT can convert statement terminating errors into batch terminating errors. It will be covered in
more detail in the T-SQL Error Handling module.
Explicit Transactions
Key Points
An explicit transaction is one in which you explicitly define both the start and end of the transaction. You
can use explicit transactions to define your own units of business logic. For example, in a bank transfer
function, you might enclose the withdrawal of funds from one account and the deposit of those funds in
another account within one logical unit of work. DB-Library applications and Transact-SQL scripts use the
BEGIN TRANSACTION, COMMIT TRANSACTION, COMMIT WORK, ROLLBACK TRANSACTION, or
ROLLBACK WORK Transact-SQL statements to define explicit transactions.
Starting a Transaction
You start a transaction by using the BEGIN TRANSACTION statement. You can specify a name for the
transaction, and you can use the WITH MARK option to specify a description for the transaction to be
marked in the transaction log. This transaction log mark can be used by database administrators when
restoring a database to indicate the point to which you want to restore. The BEGIN TRANSACTION
statement is often abbreviated to BEGIN TRAN.
Note: By default, only the statement in error would be rolled back and the batch would
continue to run and commit the other statements in the transaction.
Therefore error handling must be implemented (which will be discussed in a later module) or
XACT_ABORT can be turned on to abort the batch and rollback the whole transaction in case of an error.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-9
Committing a Transaction
You can commit the work contained in a transaction by issuing the COMMIT TRANSACTION statement.
Use this to end a transaction if no errors have occurred and you want the contents of the transaction to
be committed to the database.
The COMMIT TRANSACTION statement is often abbreviated to just the word COMMIT. To assist users
from other database platforms that are migrating to SQL Server, the statement COMMIT WORK can also
be used.
The ROLLBACK TRANSACTION statement is often abbreviated to just the word ROLLBACK. To assist users
from other database platforms that are migrating to SQL Server, the statement ROLLBACK WORK can also
be used.
Saving a Transaction
By using savepoints, you can roll back a transaction to a named point in the transaction, instead of the
beginning of the transaction. Inside the body of a transaction, create a savepoint by issuing the SAVE
TRANSACTION statement and specifying the name of the savepoint. You can then use the ROLLBACK
TRANSACTION statement and specify the savepoint name to roll the changes back to that point.
Use savepoints when an error is unlikely to occur and the cost of checking the data before the error
occurs is much higher than testing for the error after the data modifications have been submitted.
Note that while the T-SQL syntax in SQL Server supports the nesting of transactions, true nesting does not
occur. A rollback on an inner transaction also rolls back any outer transactions and a rollback on the
outermost transaction will undo any inner committed transaction.
Implicit Transactions
Key Points
When a connection is operating in implicit transaction mode, the database engine automatically starts a
new transaction after the current transaction is committed or rolled back. You do nothing to delineate the
start of a transaction; you only commit or roll back each transaction. Implicit transaction mode generates
a continuous chain of transactions.
Implicit Transactions
In most cases, it is best to work in autocommit mode and define transactions explicitly using the BEGIN
TRANSACTION statement. However for applications that were originally developed on systems other than
SQL Server, the implicit transaction mode can be useful. Implicit transaction mode automatically starts a
transaction when you issue certain statements, and the transaction then continues until you issue a
commit statement or a rollback statement.
By default, implicit transaction mode is off and the database works in autocommit mode.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-11
Nested transactions (where a transaction is started within another transaction) are not allowed in implicit
transaction mode. If the connection is already in a transaction, these statements do not start a new
transaction.
Question: Can you think of an application in your organization where implicit transactions might be
appropriate?
MCT USE ONLY. STUDENT USE PROHIBITED
13-12 Creating Highly Concurrent SQL Server 2012 Applications
Transaction Recovery
Key Points
SQL Server automatically guarantees that all committed transactions are reflected in the database in the
event of a failure. It uses the transaction log and checkpoints to do this.
Checkpoints
As each Transact-SQL statement is executed, it is recorded to the transaction log on disk before it is
written to the database and before the user is notified that the transaction was committed successfully.
SQL Server performs checkpoints at defined intervals. Checkpoints are marked in the transaction log to
identify which transactions have already been applied to the database. When a new checkpoint occurs, all
data pages in memory that have been modified since the last checkpoint are written to the database.
Transaction Recovery
If any errors occur during a transaction, the instance of SQL Server uses the information in the log file to
roll back the transaction. This rollback does not affect the work of any other users working in the database
at the same time. Usually, the error is returned to the application, and if the error indicates a possible
problem with the transaction, the application issues a ROLLBACK statement.
Some errors, such as a 1205 deadlock error, roll back a transaction automatically. If anything stops the
communication between the client and an instance of SQL Server while a transaction is active, the instance
rolls back the transaction automatically when notified of the stoppage by the network or operating
system. This could happen if the client application terminates, if the client computer is shut down or
restarted, or if the client network connection is broken. In all of these error conditions, any outstanding
transaction is rolled back to protect the integrity of the database.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-13
• Transactions 2 and 4 were committed after the checkpoint, so they must be reconstructed from the
log (rolled forward).
• Transactions 3 and 5 were not committed, so SQL Server rolls them back.
Question: A server crash occurs while two transactions are running. Transaction A is an autocommit
transaction that has been written to the transaction log, but not written to the disk. Transaction B is
an explicit transaction that has not been committed, though a checkpoint was written while
Transaction B was running. What will happen to each transaction when the server is recovered?
MCT USE ONLY. STUDENT USE PROHIBITED
13-14 Creating Highly Concurrent SQL Server 2012 Applications
Key Points
There are a number of general considerations that need to be kept in mind when working with
transactions.
• Do not require input from users during a transaction. Address issues that require user interaction
before you start the transaction. For example, if you are updating a customer record, obtain the
necessary information from the user before you begin the transaction. A golden rule here is to never
hold a transaction across a user interaction.
• Do not open a transaction while browsing through data, if at all possible. Transactions should not
start until all preliminary data analysis has been completed.
• INSERT, UPDATE, and DELETE should be the primary statements in a transaction, and they should be
written to affect the fewest number of rows. A transaction should never be smaller than a logical unit
of work.
• Access the least amount of data possible while in a transaction. This decreases the number of locked
rows and reduces contention.
• Ensure appropriate indexing is in place as this reduces the number of pages that need to be accessed
and locked.
• You should use nesting carefully, if at all, because the failure to commit or roll back a transaction
leaves locks in place indefinitely.
• You can use the @@trancount global variable to determine whether any open transactions exist and
how deeply they are nested
• While SQL Server's syntax appears to support transaction nesting, a commonly misunderstood aspect
of SQL Server transaction handling is that a ROLLBACK operation that occurs in a nested transaction
will roll back all current transactions, not just the current level. This includes any inner transactions
that have executed a COMMIT statement.
Demonstration Steps
1. Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_13_PRJ\10776A_13_PRJ.ssmssln and click Open.
3. From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file from
within Solution Explorer.
6. Follow the instructions contained within the comments of the script files.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-17
Lesson 2
Introduction to Locks
SQL Server (and many other database engines) makes extensive use of locks when ensuring isolation
between users and consistency of transactions. It is important to have an understanding of how locking
works and to understand how locking differs from blocking.
Objectives
After completing this lesson, you will be able to:
• Detail different methods of Concurrency Control
Key Points
Concurrency control is a system of controls that administers many people trying to access the same data
at the same time so they do not adversely affect each other.
Concurrency Control
SQL Server supports a wide range of optimistic and pessimistic concurrency control mechanisms.
Programmers specify the type of concurrency control by specifying the transaction isolation level for a
connection.
Concurrency control ensures that modifications made by one person do not adversely affect modifications
that others make. There are two types of concurrency control; pessimistic and optimistic.
Question: Can you think of an application in your organization that might work well with optimistic
concurrency control?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-19
Key Points
Locking is a mechanism used by the Database Engine to synchronize access by multiple users to the same
piece of data at the same time.
Locking Behavior
Before a transaction acquires a dependency on the current state of a piece of data, such as by reading or
modifying the data, it must protect itself from the effects of another transaction modifying the same data.
The transaction does this by requesting a lock on the piece of data.
Read locks allow others to read but not write data. Write locks stop others from reading or writing. In SQL
Server, these locks are implemented via different locking modes, such as shared or exclusive. The lock
mode defines the level of dependency the transaction has on the data.
No transaction can be granted a lock that would conflict with the mode of a lock already granted on that
data to another transaction. If a transaction requests a lock mode that conflicts with a lock that has
already been granted on the same data, the instance of the Database Engine will pause the requesting
transaction until the first lock is released.
When a transaction modifies a piece of data, it holds the lock protecting the modification until the end of
the transaction. How long a transaction holds the locks acquired to protect read operations depends on
the transaction isolation level setting. All locks held by a transaction are released when the transaction
completes (either commits or rolls back).
Question: If a doctor's office uses a database application to manage patient records, how might locks
play a role in that application?
MCT USE ONLY. STUDENT USE PROHIBITED
13-20 Creating Highly Concurrent SQL Server 2012 Applications
Key Points
The two terms locking and blocking are not the same thing and are often confused with each other.
Locking
Locking is the action of taking and holding locks that is used to implement concurrency control.
Blocking
Blocking is what happens to one process while it needs to wait for a resource that another process
has locked.
Blocking is a normal occurrence for systems that use locking. It is only excessive blocking that is
a problem.
Question: What symptoms do you imagine that “excessive” blocking might relate to?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-21
Key Points
Users modifying data can affect other users who are reading or modifying the same data at the same
time. These users are said to be accessing the data concurrently. If a data storage system has no
concurrency control, users could see the side effects listed on the slide.
Lost updates occur when two or more transactions select the same row and then update the row based
on the value originally selected. Each transaction is unaware of the other transactions. The last update
overwrites updates made by the other transactions, which results in lost data.
Uncommitted dependency (or dirty read) occurs when a second transaction selects a row that is being
updated by another transaction. The second transaction is reading data that has not been committed yet
and may be changed by the transaction updating the row.
Inconsistent analysis is also known as non-repeatable reads. It occurs when a second transaction accesses
the same row several times and reads different data each time. Inconsistent analysis is similar to
uncommitted dependency in that another transaction is changing the data that a second transaction is
reading. However, in inconsistent analysis, the data read by the second transaction was committed by the
transaction that made the change.
Phantom reads occur when an insert or delete action is performed against a row that belongs to a range
of rows being read by a transaction. The transaction's first read of the range of rows shows a row that no
longer exists in the second or succeeding read as a result of a deletion by a different transaction. Similarly,
the transaction's second or succeeding read shows a row that did not exist in the original read as the
result of an insertion by a different transaction.
MCT USE ONLY. STUDENT USE PROHIBITED
13-22 Creating Highly Concurrent SQL Server 2012 Applications
If another user changes the index key column of the row during your read, the row might appear again if
the key change moved the row to a position ahead of your scan. Similarly, the row might not appear if the
key change moved the row to a position in the index that you had already read.
Question: Has your organization experienced concurrency problems with database applications? If
so, what behavior did you see?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-23
Lockable Resources
Key Points
For optimal performance, the number of locks that SQL Server maintains must be balanced with the
amount of data that each lock holds. To minimize the cost of locking, SQL Server automatically locks
resources at a level that is appropriate to the task.
Question: If a database needs to lock several rows of data at once, what resources might be locked?
MCT USE ONLY. STUDENT USE PROHIBITED
13-24 Creating Highly Concurrent SQL Server 2012 Applications
Types of Locks
Key Points
SQL Server locks resources using different lock modes that determine how the resources can be
accessed by concurrent transactions. SQL Server has two main types of locks: basic locks and locks for
special situations.
Basic Locks
In general, read operations acquire shared locks, and write operations acquire exclusive locks.
• Shared locks. SQL Server typically uses shared (read) locks for operations that neither change nor
update data. If SQL Server has applied a shared lock to a resource, a second transaction also can
acquire a shared lock, even though the first transaction has not completed.
• Intent locks. SQL Server uses intent locks internally to minimize locking conflicts. Intent locks
establish a locking hierarchy so that other transactions cannot acquire locks at more inclusive levels.
For example, if a transaction has an exclusive row-level lock on a specific customer record, SQL Server
will create an intent lock at the table level which will block another transaction from acquiring an
exclusive lock at the table level.
Intent locks include intent share (IS), intent exclusive (IX), and shared with intent exclusive (SIX).
• Update locks. SQL Server uses update locks when it will modify a resource at a later point. Before it
modifies the resource, SQL Server promotes the update lock to an exclusive lock to prevent locking
conflicts.
Consider the following facts about update locks. Update locks are:
• Acquired during the initial portion of an update operation when the pages are first being read.
• Compatible with shared locks.
• Schema locks. SQL Server uses these to ensure that a table or index is not dropped, or its schema
modified, when it is referenced by another session.
Question: What happens if a query tries to read data from a row that is currently locked by an
exclusive (X) lock?
MCT USE ONLY. STUDENT USE PROHIBITED
13-26 Creating Highly Concurrent SQL Server 2012 Applications
Lock Compatibility
Key Points
Some locks are compatible with other locks, and some locks are not. For example, two users can both hold
shared locks on the same data at the same time, but only one update lock can be issued on a piece of
data at any one time.
Lock Compatibility
Locks have a compatibility matrix that shows which locks are compatible with other locks that are
established on the same resource. The locks shown in the slide are the most common forms.
The locks in the following table are listed in order from the least restrictive (shared) to the most restrictive
(exclusive).
Exclusive (X) No No No No No No
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-27
Lesson 3
Management of Locking
Locking behavior in SQL Server mostly operates without any need for management or application
intervention. However, it may be desirable in some situations to exert control over locking behavior.
Objectives
After completing this lesson, you will be able to:
Locking Timeout
Key Points
Applications might need to wait some time for locks held by other applications to be released. A key
decision is how long an application should wait for a lock to be released.
Locking Timeout
The length of time that it is reasonable to wait for a lock to be released is totally dependent upon the
design requirements of the application. By default, SQL Server will wait forever for a lock.
LOCK_TIMEOUT is a session-level setting that determines the number of milliseconds to wait for any lock
to be released before rolling back the statement (note not necessarily the transaction) and returning an
error. The default value of -1 indicates that SQL Server should wait forever.
Setting a lock timeout at the session level is not common as most applications implement query timeouts.
READPAST tells SQL Server to ignore any rows that it can't read as they are locked. It is rarely used.
Question: Can you think of any situations where READPAST might be useful?
MCT USE ONLY. STUDENT USE PROHIBITED
13-30 Creating Highly Concurrent SQL Server 2012 Applications
Lock Escalation
Key Points
Lock escalation is the process of converting many fine-grain locks into fewer coarse-grain locks, reducing
system overhead while increasing the probability of concurrency contention.
When locking rows or index key ranges, the database engine places an intent lock on the pages that
contain the rows or keys.
When locking pages, the database engine places an intent lock on the higher level objects that
contain the pages. In addition to intent lock on the object, intent page locks are requested on the
following objects:
The database engine might do both row and page locking for the same statement to minimize the
number of locks and reduce the likelihood that lock escalation will be necessary. For example, the
database engine could place page locks on a nonclustered index (if enough contiguous keys in the index
node are selected to satisfy the query) and row locks on the data.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-31
To escalate locks, the database engine attempts to change the intent lock on the table to the
corresponding full lock, for example, changing an intent exclusive (IX) lock to an exclusive (X) lock, or an
intent shared (IS) lock to a shared (S) lock). If the lock escalation attempt succeeds and the full table lock is
acquired, then all heap or B-tree, page (PAGE), or row-level (RID) locks held by the transaction on the
heap or index are released. If the full lock cannot be acquired, no lock escalation happens at that time and
the database engine will continue to acquire row, key, or page locks.
Partitioned tables can have locks escalated to the partition level before escalating to the table level.
Partition-level escalation can be set on a per-table basis. This allows for data in other partitions to be
available, so that the entire table is not locked. The ability to escalate locks to the partition-level can be
set on a per-table basis.
Question: Why do you imagine that SQL Server might find escalating locks worthwhile?
MCT USE ONLY. STUDENT USE PROHIBITED
13-32 Creating Highly Concurrent SQL Server 2012 Applications
Key Points
Deadlocks occur when demands for resources are not able to be resolved by waiting for locks to be
released, no matter how long the processes involved wait.
Deadlocks
The simplest example of a deadlock occurs when two transactions have locks on separate objects and
each transaction requests a lock on the other transaction’s object. For example:
• Transaction A requests an exclusive lock on row 2, but it cannot be granted until Transaction B
releases the shared lock.
• Transaction B requests an exclusive lock on row 1, but it cannot be granted until Transaction A
releases the shared lock.
Each transaction must wait for the other to release the lock.
A deadlock can also occur when several long-running transactions execute concurrently in the same
database. A deadlock also can occur as a result of the order in which the optimizer processes a complex
query, such as a join, in which you cannot necessarily control the order of processing.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-33
• In a deadlock, SQL Server chooses as the deadlock victim the session running the transaction that
is the least expensive to roll back.
Error 1205 is one of the errors that should be specifically checked for by applications. If error 1205 is
found, the application should attempt the transaction again.
Error 1205 is also a good example of why database engine errors should not be passed directly to end
users. Emotive words can cause emotive reactions and the message returned for error 1205 is highly
emotive. People don't like to see they have been “chosen as a deadlock victim”.
Question: Have you experienced deadlocking problems in your current environment? If so, how did
you determine that deadlocks were a problem, and how was it resolved?
MCT USE ONLY. STUDENT USE PROHIBITED
13-34 Creating Highly Concurrent SQL Server 2012 Applications
Key Points
The available locking hints are listed here for completeness. While a wide range of locking hints are
available, it is important to realize that they should rarely be used and only with extreme caution.
Key Points
Typically, you use SQL Server Management Studio to display a report of active locks. You can use SQL
Server Profiler to obtain information on a specific set of transactions. You can also use Reliability and
Performance Monitor to display SQL Server locking histories.
sys.dm_tran_locks
sys.dm_tran_active_transactions
sys.dm_tran_session_transactions
sys.dm_tran_current_transaction
You can query the sys.dm_tran_locks dynamic management view to retrieve information about the locks
currently held by an instance of the Database Engine. Each row returned describes a currently granted
lock or a requested lock.
The columns returned are divided into two main groups; the resource group which describes the resource
on which the request is made, and the request group which describes the lock request.
MCT USE ONLY. STUDENT USE PROHIBITED
13-36 Creating Highly Concurrent SQL Server 2012 Applications
In SQL Server Profiler, use the Locks Event Category to capture locking information in a trace. Extreme
care should be taken when tracing lock-related events such as Lock Acquired and Lock Released as these
events can occur many thousands of times, even for a single T-SQL statement.
Question: When would you want to choose one method of viewing locks over another?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-37
Demonstration Steps
1. If Demonstration 1A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
5. Follow the instructions contained within the comments of the script files.
MCT USE ONLY. STUDENT USE PROHIBITED
13-38 Creating Highly Concurrent SQL Server 2012 Applications
Lesson 4
Transaction Isolation Levels
The final important concept that needs to be understood when working with concurrency in SQL Server is
transaction isolation levels. It was mentioned earlier that a role of any database engine is to give each user
the best possible illusion that they are the only user on the system. This is not totally possible but
appropriate use of transaction isolation levels can help in this regard.
Objectives
After completing this lesson, you will be able to:
Key Points
An isolation level protects a transaction from the effects of other concurrent transactions. Use the
transaction isolation level to set the isolation level for all transactions during a session. When you set the
isolation level, you specify the default locking behavior for all statements in your session.
SET TRANSACTION ISOLATION LEVEL {READ COMMITTED | READ UNCOMMITTED | REPEATABLE READ |
SERIALIZABLE | SNAPSHOT}
READ UNCOMMITTED is the lowest isolation level, and only ensures that corrupt data is not read. This is
equivalent to a NOLOCK table hint. With READ UNCOMMITTED, you are sacrificing consistency in favor of
high concurrency. NOLOCK was commonly used in reporting applications before SNAPSHOT isolation
level became available. It is not safe to use NOLOCK on queries that are accessing data currently being
changed. The ability to read uncommitted data can lead to many inconsistencies.
READ COMMITTED acquires short lived share locks before reading data and released as soon as the data
is read. This is the SQL Server default. Dirty reads cannot occur but non-repeatable reads can occur.
MCT USE ONLY. STUDENT USE PROHIBITED
13-40 Creating Highly Concurrent SQL Server 2012 Applications
REPEATABLE READ retains locks on every row it touches until the end of the transaction. Even rows that
do not qualify for the query result remain locked. These locks ensure that the rows touched by the query
cannot be updated or deleted by a concurrent session until the current transaction completes (whether it
is committed or rolled back).
SNAPSHOT tries to avoid one process blocking another when only one is performing updates. As an
example, while in this isolation level, if a transaction attempts to modify a row that another transaction
has read earlier in its transaction, SQL Server creates a copy of the row in a row version table (actually held
in tempdb) and allows the update to proceed. The original transaction will now read the row from the row
version table when necessary, instead of from the table row. The original transaction would see the
unmodified version of the row.
The situation where this can lead to a problem is where the application then attempts to update the
version of the row in the row version table. If the modification to the original table row is committed, this
second modification will then fail with a concurrency violation. Note that before SNAPSHOT isolation level
can be used, it needs to be enabled via a database option.
SERIALIZABLE ensures consistency by assuming that two transactions might try to update the same data
and uses locks to ensure that they do not but at a cost of reduced concurrency - one transaction must
wait for the other to complete and two transactions can deadlock. Transactions are completely isolated
from one another.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-41
Key Points
Not every application can use snapshot isolation level as it needs to be specified when beginning a
transaction. Often this requires a change to the application code. Many existing reporting applications
cause excessive blocking. Prior to SQL Server 2005, this was commonly dealt with via NOLOCK hints.
Option Description
READ COMMITTED with Directs SQL Server to use shared locks while reading. At
READ_COMMITTED_SNAPSHOT OFF this level, you cannot experience dirty reads.
READ COMMITTED with Directs SQL Server to use row versioning instead of
READ_COMMITTED_SNAPSHOT ON locking. The data is not protected from updates made by
other transactions but the transaction will not be blocked
while reading the data.
MCT USE ONLY. STUDENT USE PROHIBITED
13-42 Creating Highly Concurrent SQL Server 2012 Applications
It is important to note though that the read committed snapshot database option does not achieve
exactly the same outcome as the snapshot isolation level set at the session level. With the read committed
snapshot database option, snapshots are only present for the duration of each statement, not for the
duration of the transaction.
Database Configuration
Before either snapshot isolation level or the read committed snapshot database option can be used, the
database needs to be configured to allow snapshot isolation.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-43
Key Points
Similar to the way table hints can be applied to control locking, the isolation-level table hints can be
applied to override the default transaction isolation level. They are listed here for completeness.
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click
SQL Server Management Studio.
3. In Connect to Server window, type Proseware in the Server name text box.
4. In the Authentication drop-down list box, select Windows Authentication and click Connect.
7. From the View menu, click Solution Explorer. In Solution Explorer, double-click the query
00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
In this lab, you will perform basic investigation of a deadlock situation. You are trying to determine an
appropriate transaction isolation level for a new application. If you have time, you will investigate the
trade-off between concurrency and consistency.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-45
Results: After this exercise, you have executed queries that create a deadlock situation. You will observe
how this can be traced in SQL Server Profiler
MCT USE ONLY. STUDENT USE PROHIBITED
13-46 Creating Highly Concurrent SQL Server 2012 Applications
Results: After this exercise, you will have seen how transaction isolation levels work.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-47
Review Questions
1. Why is snapshot isolation level helpful?
Best Practices
1. Always use the lowest transaction isolation level possible to avoid blocking and to avoid the chance
of deadlocks.
2. Many Microsoft-supplied components default to Serializable transactional isolation level but do not
need to be run at that level. Common examples are Component Services and BizTalk adapters.
3. Before spending too much time investigating blocking issues, make sure that all the queries that are
involved are executing quickly. This usually involves making sure that appropriate indexes are in
place. Often when query performance issues are resolved, blocking issues disappear.
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
14-1
Module 14
Handling Errors in T-SQL Code
Contents:
Lesson 1: Understanding T-SQL Error Handling 14-3
Lesson 2: Implementing T-SQL Error Handling 14-13
Lesson 3: Implementing Structured Exception Handling 14-24
Lab 14: Handling Errors in T-SQL Code 14-32
MCT USE ONLY. STUDENT USE PROHIBITED
14-2 Handling Errors in T-SQL Code
Module Overview
When creating applications for Microsoft® SQL Server® using the T-SQL language, appropriate handling
of errors is critically important. A large number of myths surround how error handling in T-SQL works. In
this module, you will explore T-SQL error handling; look at how it has traditionally been implemented and
how structured exception handling can be used.
Objectives
After completing this lesson, you will be able to:
Lesson 1
Understanding T-SQL Error Handling
Before delving into the coding that deals with error handling in T-SQL, it is important to gain an
understanding of the nature of errors, of where they can occur when T-SQL is being executed, the data
that is returned by errors and the severities that errors can exhibit.
Objectives
After completing this lesson, you will be able to:
• Explain where T-SQL errors occur
Key Points
T-SQL statements go through multiple phases during their execution. Errors can occur at each phase.
Some errors could potentially be handled by the database engine. Other errors will need to be passed
back to the calling application.
Syntax Check
In the first phase of execution, the syntax of a statement is checked. At this phase errors occur if the
statements do not conform to the rules of the language. During the syntax checking phase, the objects
referred to may not actually exist. Still, no errors would be returned. For example, imagine the execution
of a statement where the word “Customer” was misspelled:
There is nothing incorrect about this from a syntax point of view. The rules of the T-SQL language have
been followed. During the syntax checking phase, no error would be returned.
Object Resolution
In the second phase of execution, the objects referenced by name in the T-SQL statements are resolved to
underlying object IDs. Errors occur at this phase if the objects do not exist. Single part names are resolved
to specific objects at this point. To avoid ambiguity at this point, multi-part names should be used for
objects except in rare circumstances.
In the example above, SQL Server would first look for a table named “Custommer” in the default
schema of the user executing the code. If no such table exists, SQL Server would then look for the table
“dbo.Custommer” ie: it would next look in the dbo schema. If no such table existed in the dbo schema, an
error would then be returned.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-5
Statement Execution
In the third phase of execution, the statement is executed. At this phase, runtime errors can occur. For
example, the user may not have permission to SELECT from the table specified or an INSERT statement
might fail because a constraint was going to be violated. You could also have more basic errors occurring
at this point such as an attempt to divide by a zero value.
Some errors can be handled in the database engine but other errors will need to be handled by client
applications. Client applications always need to be written with error handling in mind.
Question: Can you suggest a reason why you might want to catch errors in a client application rather
than allowing the errors to be seen by the end users?
MCT USE ONLY. STUDENT USE PROHIBITED
14-6 Handling Errors in T-SQL Code
Types of Errors
Key Points
A number of different categories of error can occur. Mostly they differ by the scope of the termination
that occurs when the error is not handled.
Syntax Errors
Syntax errors occur when the rules of the language are not followed. For example, consider the following
statement:
If you try to execute the statement, you receive the following message:
Note that the syntax of the entire batch of statements being executed is checked before the execution of
any statement within the batch is attempted. Syntax errors are batch terminating errors.
The same issue would occur if the schema for the object was not specified and the object did not exist in
the user’s default schema or in the dbo schema. Note that if a syntax error occurs, no attempt at object
name resolution will be made.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-7
From the example you can see that the PRINT statement was still executed even though the DELETE
statement failed because of a constraint violation.
The most serious errors would terminate SQL Server itself. Errors of this nature usually indicate particularly
serious hardware errors. Fortunately such errors are rare!
MCT USE ONLY. STUDENT USE PROHIBITED
14-8 Handling Errors in T-SQL Code
What’s in an Error?
Key Points
An error is itself an object and has properties as shown in the table.
What’s in an Error
It might not be immediately obvious that a SQL Server error (or sometimes called an exception) is itself an
object. Errors return a number of useful properties.
Error numbers are helpful when trying to locate information about the specific error, particularly when
searching online for information about the error.
You can view the list of system-supplied error messages by querying the sys.messages catalog view:
Note that there are multiple messages with the same message_id. Error messages are localizable and can
be returned in a number of languages. A language_id of 1033 is the English version of the message. You
can see an English message in the third line of the output above.
Severity indicates how serious the error is. It is described further in the next topic.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-9
State is defined by the author of the code that raised the error. For example, if you were writing a stored
procedure that could raise an error for a missing customer and there were five places in the code that this
message could occur, you could assign a different state to each of the places where the message was
raised. This would help later to troubleshoot the error.
Procedure name is the name of the stored procedure that that error occurred in and Line Number is the
location within that procedure. In practice, line numbers are not very helpful and not always applicable.
Error Severity
Key Points
The severity of an error indicates the type of problem encountered by SQL Server. Low severity values are
informational messages and do not indicate true errors. Error severities occur in ranges:
Values from 0 to 10
Values from 0 to 9 are purely informational messages. When queries that raise these are executed in SQL
Server Management Studio, the information is returned but no error status information is provided. For
example, consider the following code executed against the AdventureWorks database:
When executed, it returns a count as expected. However, if you look on the Messages tab in SQL Server
Management Studio, you will see the following:
(1 row(s) affected)
Note that no error really occurred but SQL Server is warning you that it ignored NULL values when
counting the rows. Note that no status information is returned.
Values from 11 to 16
Values from 11 to 16 are considered errors that the user can correct. Typically they are used for errors
where SQL Server assumes that the statement being executed was in error.
Values from 17 to 19
Values from 17 to 19 are considered serious software errors that the user cannot correct.
Values above 19
Values above 19 tend to be very serious errors that normally involve errors with either the hardware or
SQL Server itself. It is common to ensure that all errors above 19 are logged and alerts generated on
them. Note that for errors above severity level 19, the connection is closed.
MCT USE ONLY. STUDENT USE PROHIBITED
14-12 Handling Errors in T-SQL Code
Demonstration Setup
1. Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_14_PRJ\10776A_14_PRJ.ssmssln and click Open.
3. From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file from
within Solution Explorer.
5. Follow the instructions contained within the comments of the script file.
Lesson 2
Implementing T-SQL Error Handling
Now that you understand the nature of errors, it is time to consider how they can be handled or reported
in T-SQL. The T-SQL language offers a variety of error handling capabilities. It is important to understand
these and how they relate to transactions. This lesson covers basic T-SQL error handling, including how
you can raise errors intentionally and how you can set up alerts to fire when errors occur. In the next
lesson, you will see how to implement a more advanced form of error handling known as structured
exception handling.
Objectives
After completing this lesson, you will be able to:
• Explain the role of errors and transactions
Key Points
Many new developers are surprised to find out that a statement enclosed in a transaction does not
automatically roll the transaction back when it fails; only the statement rolls back. The SET XACT_ABORT
statement can be used to control this behavior.
BEGIN TRAN;
COMMIT;
From the example you can see that both PRINT statements still execute even though the DELETE
statement failed.
SET XACT_ABORT ON
The SET XACT_ABORT ON statement is used to tell SQL Server that statement terminating errors should
become batch terminating errors.
BEGIN TRAN;
COMMIT;
From the example you can see that when the DELETE statement failed, the entire batch was terminated,
including the transaction that had begun. The transaction would have been rolled back.
MCT USE ONLY. STUDENT USE PROHIBITED
14-16 Handling Errors in T-SQL Code
Key Points
Both PRINT and RAISERROR can be used to return information or warning messages to applications.
RAISERROR allows applications to raise an error that could then be caught by the calling process.
RAISERROR
The ability to raise errors in T-SQL makes error handling in the application easier as it is sent like any other
system error. RAISERROR is used to:
Question: Why might you want to intentionally raise an error in your code?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-17
Key Points
The THROW statement offers a simpler method of raising errors in code. Errors must have an error
number of at least 50000.
THROW
THROW differs from RAISERROR in several ways:
• Errors raised by THROW only cause transaction abort when used in conjunction with SET
XACT_ABORT ON but the session is terminated
MCT USE ONLY. STUDENT USE PROHIBITED
14-18 Handling Errors in T-SQL Code
Using @@Error
Key Points
Most traditional error handling code in SQL Server applications has been created using @@ERROR. Note
that structured exception handling was introduced in SQL Server 2005 and provides a strong alternative
to using @@ERROR. It will be discussed in the next lesson. A large amount of existing SQL Server error
handling code is based on @@ERROR so it is important to understand how to work with it.
@@ERROR
@@ERROR is a system variable that holds the error number of the last error that has occurred. One
significant challenge with @@ERROR is that the value it holds is quickly reset as each additional statement
is executed.
For example, consider the following code:
You might expect that when it is executed, it would return the error number in a printed string. However,
when the code is executed, it returns:
Note that the error was raised but that the message printed was “Error=0”. You can see in the first line of
the output that the error was actually 50000 as expected with a message passed to RAISERROR. This is
because the IF statement that follows the RAISERROR statement was executed successfully and caused the
@@ERROR value to be reset.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-19
Key Points
Any ROLLBACK causes all levels of transactions to be rolled back, not just the current nesting level.
No matter how deeply you nest transactions, a ROLLBACK rolls back all levels of transaction.
SQL Server does not support autonomous transactions. Autonomous transactions are nested transactions
that are in a different transaction scope. Typically this limitation arises when trying to construct auditing
or logging code. Code that is written to log that a user attempted an action is rolled back as well when
the action is rolled back. One workaround for this is to store the values in table variables which are not
rolled back during a transaction and could be inserted from in a later separate transaction.
Nesting Levels
You can determine the current transaction nesting level by querying the @@TRANCOUNT system
variable.
Another rule to be aware of is that SQL Server requires that the transaction nesting level of a stored
procedure is the same on entry to the stored procedure and on exit from it. If the transaction nesting level
differs, error 266 is raised. This is commonly seen when users are attempting to nest transaction rollback.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-21
Key Points
Rather than raising system errors, SQL Server allows users to define custom error messages that have
meaning to their applications. The error numbers supplied must be 50001 or above and the user adding
them must be a member of the sysadmin or serveradmin fixed server roles.
Key Points
For certain categories of errors, administrators might create SQL Server Alerts, because they wish to be
notified as soon as these errors occur. This can even apply to user-defined error messages. For example,
you may wish to raise an alert whenever a transaction log fills. Alerting is commonly used to bring high-
severity errors (such as severity 19 or above) to the attention of administrators.
Raising Alerts
Alerts can be created for specific error messages. The alerting service works by registering itself as a
callback service with the event logging service. This means that alerts only work on errors that are logged.
There are two ways to make an error raise an alert. You can use the WITH LOG option when raising the
error or the message can be altered to make it logged by executing sp_altermessage. The WITH LOG
option affects only the current statement. Using sp_altermessage changes the error behavior for all future
use. Modifying system errors via sp_altermessage is only possible from SQL Server 2005 SP3 or SQL Server
2008 SP1 onwards.
Question: Can you suggest an example of an error that would require immediate attention from an
administrator?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-23
Demonstration Steps
1. If Demonstration 1A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
Lesson 3
Implementing Structured Exception Handling
Now that you have an understanding of the nature of errors and of basic error handling in T-SQL, it is
time to look at a more advanced form of error handling. Structured exception handling was introduced in
SQL Server 2005. You will see how to use it and evaluate its benefits and limitations.
Objectives
After completing this lesson, you will be able to:
• Explain TRY CATCH block programming
Key Points
Structured exception handling has been part of high level languages for some time. SQL Server 2005
introduced structured exception handling to the T-SQL language.
Centralization of error handling code also allows you to focus more on the purpose of the code rather
than on the error handling in the code.
Should a catchable error occur (most errors can be caught), execution control moves to the CATCH block.
The CATCH block is a series of T-SQL statements enclosed by BEGIN CATCH and END CATCH statements.
Note that while BEGIN CATCH and END TRY are separate statements, the BEGIN CATCH statement must
immediately follow the END TRY statement.
Current Limitations
High level languages often offer a try/catch/finally construct. It is often used to release resources
implicitly. There is no equivalent FINALLY block in T-SQL.
Question: In what situation might it have been useful to be able to raise a system error?
MCT USE ONLY. STUDENT USE PROHIBITED
14-26 Handling Errors in T-SQL Code
Key Points
CATCH blocks make the error related information available throughout the duration of the CATCH block,
including in sub-scopes such as stored procedures run from within the CATCH block.
Another key advantage of structured exception handling in T-SQL is that a series of error handling
functions have been provided and these functions retain their values throughout the CATCH block.
Separate functions are provided to provide each of the properties of an error that has been raised.
This means that you can write generic error handling stored procedures and they can still access the error
related information.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-27
Key Points
It is important to realize that while TRY/CATCH blocks allow you to catch a much wider range of errors
than you could catch with @@ERROR, you cannot catch all types of errors.
• Compile errors can occur such as syntax errors that prevent a batch from compiling.
• Statement level recompilation issues which usually relate to deferred name resolution. For example,
you could create a stored procedure that refers to an unknown table. An error is only thrown when
the procedure actually tries to resolve the name of the table to an objectid.
Question: Given the earlier discussion on the phases of execution of T-SQL statements, how could a
syntax error occur once a batch has already started executing?
MCT USE ONLY. STUDENT USE PROHIBITED
14-28 Handling Errors in T-SQL Code
Key Points
If the THROW statement is used in a CATCH block without any parameters, it will rethrow the error that
caused the code to enter the CATCH block.
In earlier versions of SQL Server, there was no method to throw a system error. While THROW cannot
specify a system error to raise, when THROW is used without parameters in a CATCH block, it will re-raise
both system and user errors.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-29
Key Points
If a transaction is current at the time an error occurs, the statement that caused the error is rolled back. If
XACT_ABORT is ON, the execution jumps to the CATCH block, instead of terminating the batch as usual.
New SQL Server developers are often surprised that a statement terminating error that occurs within a
transaction does not automatically roll that transaction back. You saw how SET XACT_ABORT ON was
used to deal with that issue. When TRY/CATCH blocks are used in conjunction with transactions and SET
XACT_ABORT is on, a statement terminating error will cause the code in the CATCH block to be executed.
However, the transaction is not automatically rolled back.
Note that at this point, no further work that would need to be committed is permitted until a rollback has
been performed. The transaction is considered to be “doomed”. After the rollback however, updates may
be made to the database, such as logging the error.
XACT_STATE()
Look at the code in the slide example. It is important to consider that when the CATCH block is entered,
the transaction may or may not have actually started. In this example, @@TRANCOUNT is being used to
determine if there is a transaction in progress and to roll back if there is one.
Another option is to use the XACT_STATE() function which provides more detailed information in this
situation. The XACT_STATE() function can be used to determine the state of the transaction:
• A value of 1 indicates that there is an active transaction which might be able to be committed.
• A value of -1 indicates that there is a current transaction but that it is doomed. The only action
permitted within the transaction is to roll it back.
MCT USE ONLY. STUDENT USE PROHIBITED
14-30 Handling Errors in T-SQL Code
Key Points
SQL CLR Integration allows for the execution of managed code within SQL Server. High level .NET
languages such as C# and VB have detailed exception handling available to them. Errors can be caught
using standard .NET try/catch/finally blocks.
It is important to realize though that any errors that are not handled in the managed code are passed
back to the calling T-SQL code. Whenever any error that occurs in managed code is returned to SQL
Server, it will appear to be a 6522 error. Errors can be nested and that error will be wrapping the real
cause of the error.
Another rare but possible cause of errors in managed code would be that the code could execute a
RAISERROR T-SQL statement via a SqlCommand object.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-31
Demonstration Steps
1. If Demonstration 1A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click
SQL Server Management Studio.
3. In Connect to Server window, type Proseware in the Server name text box.
4. In the Authentication drop-down list box, select Windows Authentication and click Connect.
7. From the View menu, click Solution Explorer. In Solution Explorer, double-click the query
00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
In this lab, a company developer asks you for assistance with some code he is modifying. The code was
written some time back and uses simple T-SQL error handling. He has heard that structured exception
handling is more powerful and wishes to use it instead.
If time permits, you will also design and implement changes to a stored procedure to provide for
automated retry on deadlock errors.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-33
Results: After this exercise, you have created a stored procedure that uses structured exception
handling.
Results: After this exercise, you have modified a stored procedure to automatically retry code for
deadlock errors.
MCT USE ONLY. STUDENT USE PROHIBITED
14-34 Handling Errors in T-SQL Code
Review Questions
1. What is the purpose of the SET XACT_ABORT ON statement?
Best Practices
When designing client-side database access code, do not assume that database operations will always
occur without error. Instead of a pattern like:
• Start a transaction
• Do some work
• While the transaction is not committed and the retry count is not exhausted, attempt to perform the
work and commit the transaction.
• If an error occurs and it is an error that retries could apply to, retry. Otherwise, return the error to the
calling code.
MCT USE ONLY. STUDENT USE PROHIBITED
15-1
Module 15
Responding to Data Manipulation via Triggers
Contents:
Lesson 1: Designing DML Triggers 15-3
Lesson 2: Implementing DML Triggers 15-12
Lesson 3: Advanced Trigger Concepts 15-19
Lab 15: Responding to Data Manipulation via Triggers 15-29
MCT USE ONLY. STUDENT USE PROHIBITED
15-2 Responding to Data Manipulation via Triggers
Module Overview
Data manipulation language (DML) triggers are a powerful tool that enables you to enforce domain,
entity, and referential data integrity and business logic. The enforcement of integrity helps you to build
reliable applications. In this lesson, you will learn what DML triggers are and how they enforce data
integrity, the different types of triggers available to you, and how to define triggers in your database.
Objectives
After completing this module, you will be able to:
Lesson 1
Designing DML Triggers
Before beginning to create DML triggers, it is important to become familiar with how they should be
designed, to avoid making common design errors. Several types of DML triggers are available. It is
important to know what they do and how they work and it is also important to understand how they
differ from Data Definition Language (DDL) triggers. DML triggers need to be able to work with both the
previous state of the database and its changed state. You will see how the inserted and deleted virtual
tables provide that capability. As DML triggers are often added after applications are built, it is important
then to make sure that adding a trigger does not cause errors in the applications that were designed
without them being in place. SET NOCOUNT ON helps avoid side effects of triggers.
Objectives
After completing this lesson, you will be able to:
• Explain how AFTER triggers differ from INSTEAD OF triggers and where each should be used
• Access both the prior and final states of the database data by using the inserted and deleted
virtual tables
• Avoid impacting existing applications by using SET NOCOUNT ON
Key Points
A DML trigger is a special kind of stored procedure that executes when an INSERT, UPDATE, or DELETE
statement modifies the data in a specified table or view. This includes any INSERT, UPDATE, or DELETE
statement that form part of a MERGE statement. A trigger can query other tables and can include
complex Transact-SQL statements.
DDL triggers are similar to DML triggers but DDL triggers fire when DDL events occur. DDL events occur
for most CREATE, ALTER or DROP statements in the T-SQL language.
Logon triggers are a special form of trigger that fire when a new session is established. There is no
concept of a Logoff trigger at present.
Trigger Operation
The trigger and the statement that fires it are treated as a single operation, which can be rolled back from
within the trigger. The ability to roll back an operation allows you to undo the effect of a T-SQL statement
if the logic in your triggers decides that the statement should not have been executed. If the statement is
part of another transaction, that outer transaction is also rolled back.
Triggers can cascade changes through related tables in the database; however, in many cases, these
changes can be executed more efficiently by using cascading referential integrity constraints.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-5
Unlike CHECK constraints, triggers can reference columns in other tables. For example, a trigger can use a
SELECT statement from another table to compare to the inserted or updated data and to perform
additional actions, such as modifying the data or displaying a user-defined error message.
Triggers can evaluate the state of a table before and after a data modification and take actions based on
that difference. For example, you may wish to check that the balance of a customer’s account does not
change by more than a certain amount, if the person processing the change is not a manager.
Triggers also allow the use of custom error messages for when constraint violations occur. This could
make the messages that are passed to end users more meaningful.
Multiple Triggers
Multiple triggers of the same type (INSERT, UPDATE, or DELETE) on a table allow multiple different actions
to take place in response to the same modification statement. Multiple triggers might be created to
separate the logic that each performs but note that you do not have complete control over the order in
which they fire. You can only specify which trigger should fire first and which should fire last.
Question: Why would you choose to use a DML trigger instead of a constraint?
MCT USE ONLY. STUDENT USE PROHIBITED
15-6 Responding to Data Manipulation via Triggers
Key Points
There are two types of DML triggers: AFTER triggers and INSTEAD OF triggers. The main difference
between them relates to when they fire. Each type of DML trigger can be implemented in either T-SQL or
in managed code. In this module, you will explore how they are designed and implemented using T-SQL.
Managed code is described in Module 16: Implementing Managed Code in Microsoft® SQL Server®.
It is important to realize that even if an UPDATE (or other data modification statement) modifies many
rows, the trigger only fires a single time. For that reason, triggers need to be designed to handle multiple
rows. This design is different to other database engines where triggers are written to target single rows
and are called multiple times when a statement affects multiple rows.
AFTER Triggers
AFTER triggers fire after the data modifications that are part of the event that they relate to completes.
This means that an INSERT, UPDATE, or DELETE statement executes and modifies the data in the database.
After that modification has completed, AFTER triggers associated with that event then fire but still within
the same operation that triggered them.
In many cases, trigger-based code can be replaced by other forms of code. For example, auditing might
be provided by SQL Server Audit (discussed in course 10775A – Administering Microsoft SQL Server 2012
Databases). Relationships between tables are more typically implemented via foreign key constraints.
Default values and calculated values are typically implemented via DEFAULT constraints and persisted
calculated columns. In some situations though, the complexity of the logic required will make triggers a
good solution.
If the trigger executes a ROLLBACK statement, the data modification statement that it is associated with
will be rolled back. If that statement was part of a larger transaction, that outer transaction would be
rolled back too.
INSTEAD OF Triggers
INSTEAD OF triggers are a special type of trigger that executes alternate code instead of executing the
statement that they were fired from.
It is important to realize that with an INSTEAD OF trigger, only the code in the trigger is executed. The
original INSERT, UPDATE, or DELETE that caused the trigger to fire does not take place.
A very common use case for INSTEAD OF triggers is to allow views that are based on multiple base tables
to be updatable.
Question: Why would the ability to run alternate code help to allow views with multiple base tables
to be updatable?
MCT USE ONLY. STUDENT USE PROHIBITED
15-8 Responding to Data Manipulation via Triggers
Key Points
When designing a trigger, it is important to be able to make decisions based on what changes have been
made to the data. To arrive at effective decisions, access is needed to details of both the unmodified and
modified versions of the data. DML triggers provide this via a pair of virtual tables called inserted and
deleted. These virtual tables are often then joined to the modified table data as part of the logic within
the trigger.
After a DELETE operation, the deleted virtual table holds details of the rows just deleted. The underlying
table no longer contains those rows. After an UPDATE operation, the deleted virtual table holds details of
the rows prior to the modification being made. The underlying table holds the modified versions.
SET NOCOUNT ON
Key Points
When adding a trigger to a table, it is important to avoid breaking any existing applications that are
accessing the table unless the intended purpose of the trigger is to prevent misbehaving applications
from making inappropriate data changes.
It is common for application programs to issue data modification statements and to check the returned
count of the number of rows affected. This is often done as part of an optimistic concurrency check. For
example, consider the following code:
UPDATE Customer
SET Customer.FullName = @NewName,
Customer.Address = @NewAddress
WHERE Customer.CustomerID = @CustomerID
AND Customer.Concurrency = @Concurrency;
In this case, the column Concurrency is a rowversion data type column. The application was designed so
that the update only occurs if the Concurrency column has not been altered. With rowversion columns,
every modification to the row causes a change in the rowversion column.
When the application intends to modify a single row, it issues an UPDATE statement for that row. The
application then checks the count of updated rows that is returned by SQL Server. When the application
sees that only a single row has been modified, the application knows that only the row it intended to
change was affected. It also knows that no other user had modified the row since the application read
the data.
A common mistake when adding triggers is that if the trigger also causes row modifications (for example,
writes an audit row into an audit table), that count is returned in addition to the expected count.
This situation can be avoided by the SET NOCOUNT ON statement. Most triggers should include this
statement.
MCT USE ONLY. STUDENT USE PROHIBITED
15-10 Responding to Data Manipulation via Triggers
Returning Rowsets
While it is possible to include a SELECT statement within a trigger and for it to return rows, the creation of
this type of side effect is discouraged. The ability to do this is now deprecated and should not be used in
new development work. There is a configuration setting ‘disallow results from triggers’ which when set to
1, disallows this capability.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-11
Trigger Considerations
Key Points
In general, constraints are preferred to triggers for performance reasons. Triggers are also complex to
debug as the actions they perform are not visible directly in the code that causes them to fire. Triggers
also increase the time taken for data modification transactions as they add extra steps that SQL Server
needs to process during these operations. Triggers should be designed to be as short as possible and to
be specific to a given task, rather than being designed to perform a large number of tasks within a single
trigger.
Note that triggers can be disabled and re-enabled via the ALTER TRIGGER statement.
Constraints are checked before any data modification is attempted and so often provide much higher
performance than is possible with triggers, particularly in ROLLBACK situations. Constraints are used when
the checks that need to be performed are relatively simple. Triggers allow complex logic to be checked.
Lesson 2
Implementing DML Triggers
Lesson 1 provided information on designing DML triggers. It is now important to consider how to
implement the designs that have been created.
Objectives
After completing this lesson, you will be able to:
Key Points
An INSERT trigger is a trigger that executes whenever an INSERT statement enters data into a table or a
view on which the trigger is configured. The action of the INSERT statement is completed before the
trigger fires but the trigger action is logically part of the INSERT operation.
The trigger can examine the inserted virtual table to determine what to do in response to the
modification.
Multi-Row Inserts
In the example shown, insertions to the table Sales.Opportunity are being audited to a table called
Sales.OpportunityAudit. Note that the trigger processes all inserted rows at once. A common error when
designing AFTER INSERT triggers is to write them with the assumption that only a single row is being
inserted.
Demonstration Steps
1. Revert the virtual machines using the instructions at D:\10776A_Labs\Revert.txt.
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, 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:\10776A_Labs\10776A_15_PRJ\10776A_15_PRJ.ssmssln and click Open.
3. From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file from
within Solution Explorer.
5. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-15
Key Points
An AFTER DELETE trigger is a trigger that executes whenever a DELETE statement removes data from a
table or view on which the trigger is configured. The action of the DELETE statement is completed before
the trigger fires but logically within the operation of the statement that fired the trigger.
The trigger can examine the deleted virtual table to determine what to do in response to the
modification.
Multi-Row Deletes
In the example shown, rows in the Product.Product table are being flagged as discontinued if the product
category row they are associated with in the Product.Category table is deleted. Note that the trigger
processes all deleted rows at once. A common error when designing AFTER DELETE triggers is to write
them with the assumption that only a single row is being deleted.
TRUNCATE TABLE
When rows are deleted from a table using a DELETE statement, any AFTER DELETE triggers are fired when
the deletion is completed. TRUNCATE TABLE is an administrative option that removes all rows from a
table. It needs additional permissions above those required for deleting rows. It does not fire any AFTER
DELETE triggers associated with the table.
Question: What performance and archival considerations should you think about when planning how
to handle deleted records?
MCT USE ONLY. STUDENT USE PROHIBITED
15-16 Responding to Data Manipulation via Triggers
Demonstration Steps
1. If Demonstration 2A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-17
Key Points
An UPDATE trigger is a trigger that executes whenever an UPDATE statement modifies data in a table or a
view on which the trigger is configured. The action of the UPDATE statement is completed before the
trigger fires.
The trigger can examine both the inserted and deleted virtual tables to determine what to do in response
to the modification.
Multi-Row Updates
In the example shown, the table Product.ProductReview contains a column called ModifiedDate. The
trigger is being used to ensure that as changes are made to the Product.ProductReview table that the
value in this column always reflects when any changes last happened. Note that the trigger processes all
updated rows at once. A common error when designing AFTER UPDATE triggers is to write them with the
assumption that only a single row is being updated.
Question: When would you imagine you might use an UPDATE trigger in your own coding?
MCT USE ONLY. STUDENT USE PROHIBITED
15-18 Responding to Data Manipulation via Triggers
Demonstration Steps
1. If Demonstration 2A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-19
Lesson 3
Advanced Trigger Concepts
In Lessons 1 and 2, you have learned to design and implement DML AFTER triggers. There are additional
areas of complexity related to triggers that also need to be understood to make effective use of them. It is
also important to understand where to use triggers and where to consider alternatives to triggers.
Objectives
After completing this lesson, you will be able to:
• Implement INSTEAD OF DML triggers
• Explain how nested triggers work and how configurations might affect their operation
• Explain additional considerations for recursive triggers, that is triggers that include actions that cause
the same trigger to fire again
• Use the UPDATE function to build logic based on the columns being updated
• Describe the limited control that can be exerted over the order that triggers fire in when multiple
triggers are defined for the same event on the same object
INSTEAD OF Triggers
Key Points
INSTEAD OF triggers cause the execution of alternate code instead of executing the statement that
caused them to fire.
Updatable Views
A very common use case for INSTEAD OF triggers is to allow views that are based on multiple base tables
to be updatable. INSTEAD OF triggers can be defined on views with one or more base tables, where they
can extend the types of updates a view can support.
This trigger executes instead of the original triggering action. INSTEAD OF triggers increase the variety of
types of updates that you can perform against a view. Each table or view is limited to one INSTEAD OF
trigger for each triggering action (INSERT, UPDATE, or DELETE).
You can specify an INSTEAD OF trigger on both tables and views. You cannot create an INSTEAD OF
trigger on views that have the WITH CHECK OPTION defined. You can perform operations on the base
tables within the trigger. This avoids the trigger being called again. For example, you could perform a set
of checks before inserting data and then perform the INSERT on the base table.
Question: What sort of situations would lead you to need to execute different statements to the data
modification statements requested?
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-21
Demonstration Steps
1. If Demonstration 2A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
Question: Why does the DELETE succeed when INSERT and UPDATE fail?
MCT USE ONLY. STUDENT USE PROHIBITED
15-22 Responding to Data Manipulation via Triggers
Key Points
Triggers can contain UPDATE, INSERT, or DELETE statements. When these statements on one table cause
triggers on another table to fire, the triggers are considered to be nested.
Nested Triggers
Triggers are often used for auditing purposes. Nested triggers are essential for full auditing to occur.
Otherwise, actions would occur on tables without being audited.
It is possible to control whether or not nested trigger actions are permitted. By default, these actions are
permitted via a configuration option at the server level. You can also detect the current nesting level by
querying @@nestlevel.
A failure at any level of a set of nested triggers cancels the entire original statement, and all data
modifications are rolled back.
A nested trigger will not fire twice in the same trigger transaction; a trigger does not call itself in response
to a second update to the same table within the trigger.
Complexity of Debugging
It was mentioned in an earlier lesson that debugging triggers can be difficult. Nested triggers are
particularly difficult to debug. One common method that is used during debugging is to include PRINT
statements within the trigger code bodies so that you can determine where a failure occurred but it is
important that these statements are only used during debugging phases.
Key Points
A recursive trigger is a trigger that performs an action that causes the same trigger to fire again either
directly or indirectly. Any trigger can contain an UPDATE, INSERT, or DELETE statement that affects the
same table or another table. With the recursive trigger option enabled on a database, a trigger that
changes data in a table can activate itself again, in a recursive execution.
Direct Recursion
Direct recursion occurs when a trigger fires and performs an action on the same table that causes the
same trigger to fire again. For example, an application updates table T1, which causes trigger Trig1 to fire.
Trig1 updates table T1 again, which causes trigger Trig1 to fire again.
Indirect Recursion
Indirect recursion occurs when a trigger fires and performs an action that causes another trigger to fire on
a different table, which subsequently causes an update to occur on the original table. This, then, causes
the original trigger to fire again. For example, an application updates table T2, which causes trigger Trig2
to fire. Trig2 updates table T3, which causes trigger Trig3 to fire. Trig3 in turn updates table T2, which
causes Trig2 to fire again.
To prevent indirect recursion of this sort, turn off the nested triggers option at the server instance level.
Question: Think of a database containing genealogy data. How might a recursive trigger be used
when a relationship between two people is corrected (such as from child and parent to grandchild
and grandparent, with an intermediate generation inserted)?
MCT USE ONLY. STUDENT USE PROHIBITED
15-24 Responding to Data Manipulation via Triggers
UPDATE Function
Key Points
It is a common requirement to build logic that only takes action if particular columns are being updated.
UPDATE Function
The UPDATE function should not be confused with the UPDATE statement. The UPDATE function allows
detection of whether or not a particular column is being updated in the action of an UPDATE statement.
For example, you might wish to take a particular action only when the Size of a product changes.
The column is referenced by the name of the column.
Change of Value
Note that this function does not indicate if the value is actually changing. It only indicates if the column is
part of the list of columns in the SET clause of the UPDATE statement. To detect if the value in a column is
actually being changed to a different value, the inserted and deleted virtual tables need to be
interrogated.
COLUMNS_UPDATED Function
SQL Server also provides a function called COLUMNS_UPDATED. This function returns a bitmap that
indicates which columns are being updated. The values in the bitmap depend upon the positional
information for the columns. Hard-coding that sort of information in the code within a trigger is generally
not considered good coding practice as it affects the readability (and hence the maintainability) of your
code. It also reduces the reliability of your code as schema changes to the table could break the code.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-25
Key Points
It is possible to assign multiple triggers to a single event on a single object. Only limited control is
available over the firing order of these triggers.
sp_settriggerorder
Developers often seek to control the firing order of multiple triggers defined for a single event on a single
object. For example, a developer might create three AFTER INSERT triggers on the same table, each
implementing different business rules or administrative tasks.
In general, code within one trigger should not depend upon the order of execution of other triggers.
Limited control of firing order is available through the sp_settriggerorder system stored procedure. It
allows you to specify which trigger fires first and which trigger fires last, from a set of triggers that all
apply to the same event on the same object.
The value for the @order parameter is either First, Last, or None. None is the default action. An error will
occur if the First and Last triggers both refer to the same trigger.
The value for the @stmttype parameter is INSERT, UPDATE, or DELETE for DML triggers.
MCT USE ONLY. STUDENT USE PROHIBITED
15-26 Responding to Data Manipulation via Triggers
Key Points
Triggers allow for complex logic and are sometimes necessary. Triggers are often though, used in
situations where other alternatives would be preferable.
Checking Values
Triggers could be used to check that values in columns are valid or within given ranges. In general, CHECK
constraints should be used for this instead of triggers as they are checked before the data modification is
attempted.
If the trigger is being used to check the correlation of values across multiple columns within the table, in
general table-level CHECK constraints should be created instead.
Defaults
Triggers can be used to provide default values for columns when no values have been provided in INSERT
statements. DEFAULT constraints should generally be used for this instead.
Foreign Keys
Triggers can be used to check the relationship between tables. In general, FOREIGN KEY constraints
should be used for this.
Computed Columns
Triggers can be used to maintain the value in one column based on the value in other columns. In
general, computed columns or persisted computed columns should be used for this.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-27
Pre-calculating Aggregates
Triggers can be used to maintain pre-calculated aggregates in one table, based on the values in rows in
another table. In general, indexed views should be used to provide this functionality.
As another example, a FOREIGN KEY cannot be contained on a column that is also used for other
purposes. Consider a column that holds an employee number only if another column holds the value ‘E’.
While this typically indicates a poor database design, triggers can be used to ensure this sort of
relationship.
MCT USE ONLY. STUDENT USE PROHIBITED
15-28 Responding to Data Manipulation via Triggers
Demonstration Steps
1. If Demonstration 2A was not performed:
• From the View menu, click Solution Explorer. Open and execute the 00 – Setup.sql script file
from within Solution Explorer.
3. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-29
Lab Setup
For this lab, you will use the available virtual machine environment. Before you begin the lab, you must
complete the following steps:
2. In the virtual machine, click Start, click All Programs, click Microsoft SQL Server 2012, and click
SQL Server Management Studio.
3. In Connect to Server window, type Proseware in the Server name text box.
4. In the Authentication drop-down list box, select Windows Authentication and click Connect.
7. From the View menu, click Solution Explorer. In Solution Explorer, double-click the query
00-Setup.sql. When the query window opens, click Execute on the toolbar.
Lab Scenario
You are required to audit any changes to data in a table that hold sensitive balance data. You have
decided to implement this via DML triggers as the requirements in this case are not provided for directly
by the SQL Server Audit mechanism.
MCT USE ONLY. STUDENT USE PROHIBITED
15-30 Responding to Data Manipulation via Triggers
Supporting Documentation
The Marketing.CampaignAudit table is used to hold audit entries. When inserting rows into this table, the
data required in each column is as shown in the following table:
Note: Inserts or Deletes to the table do not need to be audited. Details of the current user
can be taken from the function ORIGINAL_LOGIN().
2. Design a trigger to meet the requirements as stated in the scenario for this exercise.
3. Write code to test the behavior of the trigger.
f Task 2: Design a trigger to meet the requirements as stated in the scenario for this
exercise
• Design and create a trigger that meets the needs identified in Task 1.
Results: After this exercise, you should have created a new trigger. Tests should have shown that it is
working as expected.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-31
Results: After this exercise, you should have altered the trigger. Tests should show it is now working as
expected.
MCT USE ONLY. STUDENT USE PROHIBITED
15-32 Responding to Data Manipulation via Triggers
Review Questions
1. How do constraints and triggers differ regarding timing of execution?
2. Why would you use the UPDATE function rather than the COLUMNS_UPDATED function when
designing a trigger?
Best Practices
1. In many business scenarios, it makes sense to mark records as deleted with a status column and use a
trigger or stored procedure to update an audit trail table. The changes can then be audited, the data
is not lost, and the IT staff can perform purges or archival of the deleted records.