10776A ENU TrainerHandbook Part2

You might also like

You are on page 1of 238

MCT USE ONLY.

STUDENT USE PROHIBITED


O F F I C I A L M I C R O S O F T L E A R N I N G P R O D U C T

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.

Microsoft and the trademarks listed at


http://www.microsoft.com/about/legal/en/us/IntellectualProperty/Trademarks/EN-US.aspx are trademarks of
the Microsoft group of companies. All other trademarks are property of their respective owners

Product Number: 10776A

Part Number: X18-28011

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.

a. If you are a Authorized Learning Center:


i. If the Licensed Content is in digital format for each license you acquire you may either:
1. install one (1) copy of the Licensed Content in the form provided to you on a dedicated, secure
server located on your premises where the Authorized Training Session is held for access and
use by one (1) End User attending the Authorized Training Session, or by one (1) MCT teaching
the Authorized Training Session, or
2. install one (1) copy of the Licensed Content in the form provided to you on one (1) Classroom
Device for access and use by one (1) End User attending the Authorized Training Session, or by
one (1) MCT teaching the Authorized Training Session.
ii. You agree that:
1. you will acquire a license for each End User and MCT that accesses the Licensed Content,
2. each End User and MCT will be presented with a copy of this agreement and each individual
will agree that their use of the Licensed Content will be subject to these license terms prior to
their accessing the Licensed Content. Each individual will be required to denote their
acceptance of the EULA in a manner that is enforceable under local law prior to their accessing
the Licensed Content,
3. for all Authorized Training Sessions, you will only use qualified MCTs who hold the applicable
competency to teach the particular MOC Course that is the subject of the training session,
4. you will not alter or remove any copyright or other protective notices contained in the
Licensed Content,
MCT USE ONLY. STUDENT USE PROHIBITED
5. you will remove and irretrievably delete all Licensed Content from all Classroom Devices and
servers at the end of the Authorized Training Session,
6. you will only provide access to the Licensed Content to End Users and MCTs,
7. you will only provide access to the Trainer Content to MCTs, and
8. any Licensed Content installed for use during a training session will be done in accordance
with the applicable classroom set-up guide.

b. If you are a MPN Member.


i. If the Licensed Content is in digital format for each license you acquire you may either:
1. install one (1) copy of the Licensed Content in the form provided to you on (A) one (1)
Classroom Device, or (B) one (1) dedicated, secure server located at your premises where
the training session is held for use by one (1) of your employees attending a training session
provided by you, or by one (1) MCT that is teaching the training session, or
2. install one (1) copy of the Licensed Content in the form provided to you on one (1)
Classroom Device for use by one (1) End User attending a Private Training Session, or one (1)
MCT that is teaching the Private Training Session.
ii. You agree that:
1. you will acquire a license for each End User and MCT that accesses the Licensed Content,
2. each End User and MCT will be presented with a copy of this agreement and each individual
will agree that their use of the Licensed Content will be subject to these license terms prior
to their accessing the Licensed Content. Each individual will be required to denote their
acceptance of the EULA in a manner that is enforceable under local law prior to their
accessing the Licensed Content,
3. for all training sessions, you will only use qualified MCTs who hold the applicable
competency to teach the particular MOC Course that is the subject of the training session,
4. you will not alter or remove any copyright or other protective notices contained in the
Licensed Content,
5. you will remove and irretrievably delete all Licensed Content from all Classroom Devices and
servers at the end of each training session,
6. you will only provide access to the Licensed Content to End Users and MCTs,
7. you will only provide access to the Trainer Content to MCTs, and
8. any Licensed Content installed for use during a training session will be done in accordance
with the applicable classroom set-up guide.

c. If you are an End User:


You may use the Licensed Content solely for your personal training use. If the Licensed Content is in
digital format, for each license you acquire you may (i) install one (1) copy of the Licensed Content in
the form provided to you on one (1) Personal Device and install another copy on another Personal
Device as a backup copy, which may be used only to reinstall the Licensed Content; or (ii) print one (1)
copy of the Licensed Content. You may not install or use a copy of the Licensed Content on a device
you do not own or control.
MCT USE ONLY. STUDENT USE PROHIBITED
d. If you are a MCT.
i. For each license you acquire, you may use the Licensed Content solely to prepare and deliver an
Authorized Training Session or Private Training Session. For each license you acquire, you may
install and use one (1) copy of the Licensed Content in the form provided to you on one (1) Personal
Device and install one (1) additional copy on another Personal Device as a backup copy, which may
be used only to reinstall the Licensed Content. You may not install or use a copy of the Licensed
Content on a device you do not own or control.

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.3 Reproduction/Redistribution Licensed Content. Except as expressly provided in the applicable


installation and use rights above, you may not reproduce or distribute the Licensed Content or any portion
thereof (including any permitted modifications) to any third parties without the express written permission
of Microsoft.

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.

13. APPLICABLE LAW.


a. United States. If you acquired the Licensed Content in the United States, Washington state law governs
the interpretation of this agreement and applies to claims for breach of it, regardless of conflict of laws
principles. The laws of the state where you live govern all other claims, including claims under state
consumer protection laws, unfair competition laws, and in tort.

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.

LIMITATION DES DOMMAGES-INTÉRÊTS ET EXCLUSION DE RESPONSABILITÉ POUR LES DOMMAGES. Vous


pouvez obtenir de Microsoft et de ses fournisseurs une indemnisation en cas de dommages directs uniquement
à hauteur de 5,00 $ US. Vous ne pouvez prétendre à aucune indemnisation pour les autres dommages, y
compris les dommages spéciaux, indirects ou accessoires et pertes de bénéfices.
Cette limitation concerne:
• tout ce qui est relié au le contenu sous licence , aux services ou au contenu (y compris le code)
figurant sur des sites Internet tiers ou dans des programmes tiers ; et
• les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité
stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.

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.

Revised March 2012


MCT USE ONLY. STUDENT USE PROHIBITED
xiv Developing Microsoft® SQL Server® 2012 Databases
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft® SQL Server® 2012 Databases xv

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.

Design and Development


This course was designed and developed by SolidQ. SolidQ is a global provider of consulting, mentoring
and training services for Microsoft Data Management, Business Intelligence and Collaboration platforms.

Greg Low – Lead Developer


Dr Greg Low is a SQL Server MVP, an MCT, and a Microsoft Regional Director for Australia. Greg has
worked with SQL Server since version 4.2 as an active mentor, consultant and trainer. Greg describes
himself as a SQL Server junkie and also describes himself as having been involved in development since
dinosaurs roamed the Earth. He has been an instructor in the Microsoft SQL Server Masters certification
program for several years and was one of the first two people to achieve the SQL Server 2008 Master
certification. He is the author of a number whitepapers on the Microsoft MSDN and TechNet web sites
and the author of a number of SQL Server related books. Greg is based in Melbourne Australia.

Herbert Albert – Course Developer


Herbert Albert started his career in 1994. He works as a trainer, consultant, and author focusing on SQL
Server technologies. Herbert is a mentor and the Central European CEO for SolidQ. He is based in Vienna,
Austria. He has several Microsoft certifications including MCT which he has held since 1997. Herbert is a
regular speaker at conferences and co-author of the SQL Server 2012 Upgrade Technical Reference Guide
and SQL Server 2005 Step-by-Step Applied Techniques. Together with Gianluca Hotz, Herbert writes a
regular column at the SolidQ Journal.

Chris Barker – Technical Reviewer


Chris Barker is an MCT in New Zealand and currently employed as a staff trainer at Auldhouse, one of
New Zealand’s major CPLS training centers in Wellington. He has been programming from the early
1970s—his first program was written in assembly language and debugged in binary (literally)! While
focusing training on programming (mostly .NET) and databases (mostly Microsoft SQL Server), Chris has
also been an infrastructure trainer and has both Novell and Microsoft networking qualifications.

Mark Hions – Technical Reviewer


Mark's passion for computing and skill as a communicator were well suited to his position as an instructor
at Honeywell Canada, where he started working with minicomputers, mainframes, and mature students in
1984. He first met Microsoft SQL Server when it ran on OS/2, and has delivered training on every version
since. An independent MCT and consultant for many years, he is a highly-rated presenter at TechEd, has
designed SQL Server exams for Microsoft, and has delivered deep-dive courses through the Microsoft
Partner Channel. Mark is now the Principal SQL Server Instructor and Consultant at DesTech, which is the
largest provider of SQL Server training in the Toronto area.
MCT USE ONLY. STUDENT USE PROHIBITED
xvi Developing Microsoft® SQL Server® 2012 Databases

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 2: Working with Data Types


Lesson 1: Using Data Types 2-3
Lesson 2: Working with Character Data 2-16
Lesson 3: Converting Data Types 2-25
Lesson 4: Working with Specialized Data Types 2-33
Lab 2: Working with Data Types 2-39

Module 3: Designing and Implementing Tables


Lesson 1: Designing Tables 3-3
Lesson 2: Working with Schemas 3-14
Lesson 3: Creating and Altering Tables 3-19
Lab 3: Designing and Implementing Tables 3-29

Module 4: Ensuring Data Integrity through Constraints


Lesson 1: Enforcing Data Integrity 4-3
Lesson 2: Implementing Domain Integrity 4-9
Lesson 3: Implementing Entity and Referential Integrity 4-17
Lab 4: Ensuring Data Integrity through Constraints 4-31

Module 5: Planning for SQL Server 2012 Indexing


Lesson 1: Core Indexing Concepts 5-3
Lesson 2: Data Types and Indexes 5-11
Lesson 3: Single Column and Composite Indexes 5-19
Lab 5: Planning for SQL Server Indexing 5-24

Module 6: Implementing Table Structures in SQL Server 2012


Lesson 1: SQL Server Table Structures 6-3
Lesson 2: Working with Clustered Indexes 6-13
Lesson 3: Designing Effective Clustered Indexes 6-19
Lab 6: Implementing Table Structures in SQL Server 6-22
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft® SQL Server® 2012 Databases xvii

Module 7: Reading SQL Server 2012 Execution Plans


Lesson 1: Execution Plan Core Concepts 7-3
Lesson 2: Common Execution Plan Elements 7-12
Lesson 3: Working with Execution Plans 7-22
Lab 7: Reading SQL Server Execution Plans 7-28

Module 8: Improving Performance through Nonclustered Indexes


Lesson 1: Designing Effective Nonclustered Indexes 8-3
Lesson 2: Implementing Nonclustered Indexes 8-10
Lesson 3: Tracing and Tuning Queries 8-18
Lab 8: Improving Performance through Nonclustered Indexes 8-24

Module 9: Designing and Implementing Views


Lesson 1: Introduction to Views 9-3
Lesson 2: Creating and Managing Views 9-10
Lesson 3: Performance Considerations for Views 9-19
Lab 9: Designing and Implementing Views 9-27

Module 10: Designing and Implementing Stored Procedures


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

Module 11: Merging Data and Passing Tables


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

Module 12: Designing and Implementing User-Defined Functions


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
xviii Developing Microsoft® SQL Server® 2012 Databases

Module 13: Creating Highly Concurrent SQL Server 2012 Applications


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

Module 14: Handling Errors in T-SQL Code


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

Module 15: Responding to Data Manipulation via Triggers


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

Module 16 Implementing Managed Code in SQL Server 2012


Lesson 1: Introduction to SQL CLR Integration 16-3
Lesson 2: Importing and Cataloging Assemblies 16-14
Lesson 3: Implementing SQL CLR Integration 16-21
Lab 16: Implementing Managed Code in SQL Server 16-39

Module 17: Storing XML Data in SQL Server 2012


Lesson 1: Introduction to XML and XML Schemas 17-3
Lesson 2: Storing XML Data and Schemas in SQL Server 17-15
Lesson 3: Implementing XML Indexes 17-26
Lab 17: Storing XML Data in SQL Server 17-31

Module 18: Querying XML Data in SQL Server 2012


Lesson 1: Using the T-SQL FOR XML Statement 18-3
Lesson 2: Getting Started with XQuery 18-15
Lesson 3: Shredding XML 18-26
Lab 18: Querying XML Data in SQL Server 18-35

Module 19: Working with SQL Server 2012 Spatial Data


Lesson 1: Introduction to Spatial Data 19-3
Lesson 2: Working with SQL Server Spatial Data Types 19-12
Lesson 3: Using Spatial Data in Applications 19-25
Lab 19: Working with SQL Server Spatial Data 19-35
MCT USE ONLY. STUDENT USE PROHIBITED
Developing Microsoft® SQL Server® 2012 Databases xix

Module 20 Working with Full-Text Indexes and Queries


Lesson 1: Introduction to Full-Text Indexing 20-3
Lesson 2: Implementing Full-Text Indexes in SQL Server 20-9
Lesson 3: Working with Full-Text Queries 20-20
Lab 20: Working with Full-Text Indexes and Queries 20-32

Appendix: Lab Answer Keys


Module 1 Lab: Introduction to SQL Server and its Toolset L1-1
Module 2 Lab: Working with Data Types L2-5
Module 3 Lab: Designing and Implementing Tables L3-9
Module 4 Lab: Ensuring Data Integrity through Constraints L4-13
Module 5 Lab: Planning for SQL Server Indexing L5-16
Module 6 Lab: Implementing Table Structures in SQL Server L6-20
Module 7 Lab: Reading SQL Server Execution Plans L7-24
Module 8 Lab: Improving Performance through Nonclustered Indexes L8-29
Module 9 Lab: Designing and Implementing Views L9-34
Module 10 Lab: Designing and Implementing Stored Procedures L10-38
Module 11 Lab: Passing Tables and Merging Data L11-42
Module 12 Lab: Designing and Implementing User-defined Functions L12-45
Module 13 Lab: Creating Highly Concurrent SQL Server Applications L13-50
Module 14 Lab: Handling Errors in T-SQL Code L14-52
Module 15 Lab: Responding to Data Manipulation via Triggers L15-55
Module 16 Lab: Implementing Managed Code in SQL Server L16-58
Module 17 Lab: Storing XML Data in SQL Server L17-62
Module 18 Lab: Querying XML Data in SQL Server L18-65
Module 19 Lab: Working with SQL Server Spatial Data L19-68
Module 20 Lab: Working with Full-Text Indexes and Queries L20-71
MCT USE ONLY. STUDENT USE PROHIBITED
MCT USE ONLY. STUDENT USE PROHIBITED
10-1

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

• Implement parameterized stored procedures

• Control the execution context of a stored procedure


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-3

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 the potential benefits of using stored procedures

• Work with system 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

What Is a Stored Procedure?

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.

T-SQL Code and Logic Reuse


When applications interact with SQL Server there are two basic ways that they can send commands to the
server. The application could send each batch of T-SQL commands to the server to be executed and
resend the same commands if the same function needs to be executed again later.

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

Benefits of Stored Procedures

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

Working with System Stored Procedures

Key Points
SQL Server is supplied with a large amount of pre-built functionality shipped within system stored
procedures and system extended stored procedures.

Types of System Stored Procedures


There are two basic types of system stored procedures: system stored procedures and system extended
stored procedures. Both are supplied pre-built with SQL Server. The core difference between the two is
that the code for system stored procedures is written in T-SQL and is supplied in the master database
installed with SQL Server, whereas the code for the system extended stored procedures is written in
unmanaged native code (typically written in C++) and supplied via a DLL (dynamic link library). Note that
since SQL Server 2005, the objects that are accessed by the procedures are actually located in a hidden
resource database rather than directly in the master database but the effect is the same.

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


System stored procedures are “special” in that they can be executed from within any database without
needing to specify the master database as part of their name. They are typically used for administrative
tasks relating to configuring servers, databases and objects or for retrieving information about them.

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

System Extended Stored Procedures


System extended stored procedures are used to extend the functionality of the server in ways that cannot
be achieved via T-SQL code alone. Examples of system extended stored procedures are sys.xp_dirtree,
sys.xp_cmdshell and sys.sp_trace_create. (Note how the last example here has an sp_ prefix).

User Extended Stored Procedures


While it is still possible to create user-defined extended stored procedures and attach them to SQL Server,
the ability to do so is now deprecated. Extended stored procedures run directly within the memory space
of SQL Server. This is not a safe place for users to be executing code. User-defined extended stored
procedures are well-known to the SQL Server product support group as a source of problems difficult to
resolve.

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

Statements Not Permitted in Stored Procedures

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.

Statements not Permitted


Most T-SQL statements can be used within the bodies of stored procedures. For the statements that are
not permitted, the reason usually relates to one of the following:

• creation of other objects

• changing SET options that relate to query plans

• changing database context via the USE statement


Note that stored procedures can access objects in other databases but that they need to be referred to by
name, not by attempting to change the database context to another database ie: the USE statement
cannot be used within the body of a stored procedure in the way that it can be used in a T-SQL script.
MCT USE ONLY. STUDENT USE PROHIBITED
10-10 Designing and Implementing Stored Procedures

Demonstration 1A: Working with System Stored Procedures and Extended


Stored Procedures

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:

• Create a stored procedure


• Execute stored procedures

• Alter a stored procedure

• Drop a stored procedure


• Identify stored procedure dependencies

• Explain guidelines for creating stored procedures

• Obfuscate stored procedure definitions


MCT USE ONLY. STUDENT USE PROHIBITED
10-12 Designing and Implementing Stored Procedures

Creating a Stored Procedure

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

Executing Stored Procedures

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.

Two-Part Naming on Referenced Objects


It is very important when creating stored procedures to use at least two-part names for objects referenced
by the stored procedure. If you refer to a table by both its schema name and its table name, you avoid
any ambiguity about which table you are referring to and you maximize the chance of SQL Server being
able to reuse query execution plans for the stored procedure.

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

Two-Part Naming When Creating Stored Procedures


If you create a stored procedure by only supplying the name of the procedure (and not the schema name
as well), SQL Server will attempt to create the stored procedure in your default schema. Scripts that create
stored procedures this way tend to be fragile as the location of the created stored procedure would
depend upon the default schema of the user executing the script.

Two-Part Naming When Executing Stored Procedures


When you execute a stored procedure, you should also supply the name of both the schema and the
stored procedure. If you supply only the name of the stored procedure, SQL Server can end up trying to
find the stored procedure in a number of places:

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

Altering a Stored Procedure

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

Dropping a Stored Procedure

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.

sys.procedures System View


You can see a list of existing procedures in the current database by querying the sys.procedures view
which will show you the list of procedures in the current database.

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

Stored Procedure Dependencies

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

Guidelines for Creating Stored Procedures

Key Points
There are a number of important guidelines that should be considered when creating stored procedures.

Qualify Names Inside of Stored Procedures


Earlier in this lesson, the importance of using at least two-part naming when referring to objects within
stored procedure was described. This applies to both the creation of stored procedures and to their
execution.

Keep Consistent SET Options


The Database Engine saves the settings of both SET QUOTED_IDENTIFIER and SET ANSI_NULLS when a
Transact-SQL stored procedure is created or altered. These original settings are used when the stored
procedure is executed.

Apply Consistent Naming Conventions


It is recommended that you do not create any stored procedures using sp_ as a prefix. SQL Server uses the
sp_ prefix to designate system stored procedures. The name you choose may conflict with some future
system procedure.

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

Use @@nestlevel to See Current Nesting Level


Stored procedures are nested when one stored procedure calls another or executes managed code by
referencing a CLR routine, type, or aggregate. You can nest stored procedures and managed code
references up to 32 levels. You can use @@nestlevel for checking the nesting level of the current stored
procedure execution.

Keep One Procedure Per Task


Avoid writing “the procedure to rule them all” (with apologies to JRR Tolkein and the Lord of the Rings).
Don't write one procedure that does an enormous number of tasks. Doing this limits reuse possibilities
and can hinder performance.
MCT USE ONLY. STUDENT USE PROHIBITED
10-20 Designing and Implementing Stored Procedures

Obfuscating Stored Procedure Definitions

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 2A: 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 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:

• Parameterize stored procedures

• Work with input parameters

• Work with output parameters

• 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

Working with Parameterized Stored Procedures

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

Using Input Parameters

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:

CREATE PROCEDURE Sales.OrdersByDueDateAndStatus


@DueDate datetime, @Status tinyint = 5
AS

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 Input Parameters


As a best practice validate all incoming parameter values at the beginning of a stored procedure to trap
missing and invalid values early. This might include checking whether the parameter is NULL.

Validating parameters early avoids doing substantial work in the procedure and then having to undo all
that work.

Executing a Stored Procedure with Input Parameters


Three examples of executing the stored procedure are shown on the slide. Look at the first option:

EXEC Sales.OrdersByDueDateAndStatus '20050613',8;

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.

Now look at the second option:

EXEC Sales.OrdersByDueDateAndStatus '20050713';

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:

EXEC Sales.OrdersByDueDateAndStatus @DueDate = '20050713',


@Status = 5;

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:

EXEC Sales.OrdersByDueDateAndStatus @Status = 5,


@DueDate = '20050713';
MCT USE ONLY. STUDENT USE PROHIBITED
10-26 Designing and Implementing Stored Procedures

Using Output Parameters

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.

Output Parameter Requirements


• The keyword OUTPUT must be specified when declaring the output parameters of the stored
procedure.

• 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:

CREATE PROC Sales.GetOrderCountByDueDate


@DueDate datetime, @OrderCount int OUTPUT
AS

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.

Now look at how the procedure is called:

DECLARE @DueDate datetime = '20050713';


DECLARE @OrderCount int;
EXEC Sales.GetOrderCountByDueDate @DueDate,
@OrderCount OUTPUT;
SELECT @OrderCount;

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

Parameter Sniffing and Performance

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.

sp_recompile System Stored Procedure


If you call sp_recompile, any existing plans for the stored procedure passed to it will be marked as invalid
and the procedure will be recompiled next time it is executed. You can also pass the name of a table or
view to this procedure. In that case, all existing plans that reference the object will be invalidated and
recompiled the next time they are executed.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-29

EXEC WITH RECOMPILE


If you add WITH RECOMPILE to the EXEC statement, SQL Server will recompile the procedure before
running it and will not store the resulting plan. In this case, the original plan would be preserved and can
be reused later.

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.

You can see an example of this in the following code:

CREATE PROCEDURE dbo.GetProductNames


@ProductIDLimit int
AS
BEGIN
SELECT ProductID,Name
FROM Production.Product
WHERE ProductID < @ProductIDLimit
OPTION (OPTIMIZE FOR (@ProductIDLimit = 1000))
END;

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 3A: Passing Parameters to 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.

Question: Why do we need to treat NULL differently to other possible values?


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-31

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:

• Control execution context

• Work with the EXECUTE AS clause

• View execution context


MCT USE ONLY. STUDENT USE PROHIBITED
10-32 Designing and Implementing Stored Procedures

Controlling Execution Context

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 and Login Security Tokens


A security token for a user or login contains the following:

• One server or database principal as the primary identity

• One or more principals as secondary identities

• Zero or more authenticators

• The privileges and permissions of the primary and secondary identities


Login Token: A login token is valid across the instance of SQL Server. It contains the primary and
secondary identities against which server-level permissions and any database-level permissions associated
with these identities are checked. The primary identity is the login itself. The secondary identity includes
permissions inherited from rules and groups.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-33

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.

Controlling Execution Context


While the default behavior of execution contexts is usually appropriate, there are times when it is
desirable to execute within a different security context.

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.

Question: What is an authenticator?


MCT USE ONLY. STUDENT USE PROHIBITED
10-34 Designing and Implementing Stored Procedures

The EXECUTE AS Clause

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

Viewing Execution Context

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.

sys.login_token System View


The sys.login_token system view shows all tokens associated with the login. This will include the login itself
and the roles that the user is a member of. In the example shown in the slide, the Windows login
GREGW701\Greg has associated server tokens for the public and sysadmin roles.

sys.user_token System View


The sys.user_token system view shows all tokens associated with the user within the database. In the
example shown in the slide, the user is a member of the dbo role for the current database.
MCT USE ONLY. STUDENT USE PROHIBITED
10-36 Designing and Implementing Stored Procedures

Demonstration 4A: Viewing Execution Context

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 10: Designing and Implementing Stored


Procedures

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.
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.
5. In the File menu, click Open, and click Project/Solution.
6. In the Open Project window, open the project
D:\10776A_Labs\10776A_10_PRJ\10776A_10_PRJ.ssmssln.
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 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

Input Parameters: None

Output Parameters: None

Output Columns: Color (from Marketing.Product)

Output Order: Color

Notes: Colors should not be returned more than once in the output. NULL values
should not be returned.

Stored Procedure Reports.GetProductsAndModels

Input Parameters: None

Output Parameters: None

Output Columns: ProductID, ProductName, ProductNumber, SellStartDate, SellEndDate and Color


(from Marketing.Product),
ProductModelID (from Marketing.ProductModel), EnglishDescription,
FrenchDescription, ChineseDescription.

Output Order: ProductID, ProductModelID

Notes: For descriptions, return the Description column from the


Marketing.ProductDescription table for the appropriate language. The
LanguageID for English is 'en', for French is 'fr' and for Chinese is 'zh-cht'. If no
specific language description is available, return the invariant language
description if it is present. The LanguageID for the invariant language is a blank
string ''. Where neither the specific language or invariant language descriptions
exist, return the ProductName instead.

Stored Procedure Reports.GetProductsByColor

Input Parameters: @Color (same datatype as the Color column in the Marketing.Product table)

Output Parameters: None

Output Columns: ProductID, ProductName, ListPrice (returned as a column named Price), Color,
Size and SizeUnitMeasureCode (returned as a column named UnitOfMeasure)
(from Marketing.Product)

Output Order: ProductName

Notes: The procedure should return products that have no Color if the parameter is
NULL.

Input Parameters: None


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 10-39

(continued)

Stored Procedure Reports.GetProductColors

Output Parameters: None

Output Columns: Color (from Marketing.Product)

Output Order: Color

Notes: Colors should not be returned more than once in the output.
NULL values should not be returned.

Exercise 1: Create Stored Procedures


Scenario
In this exercise, you will create two stored procedures to support one of the new reports.

The main tasks for this exercise are as follows:


1. Review the Reports.GetProductColors stored procedure specification.
2. Design, create and test the Reports.GetProductColors stored procedure.
3. Review the Reports.GetProductsAndModels stored procedure specification.
4. Design, create and test the Reports.GetProductsAndModels stored procedure.

f Task 1: Review the Reports.GetProductColors stored procedure specification


• Review the Reports.GetProductColors specification in the supporting documentation.

f Task 2: Design, create and test the Reports.GetProductColors stored procedure


• Design, create and test the stored procedure based on the specifications given in the supporting
documentation for the exercise.

f Task 3: Review the Reports.GetProductsAndModels stored procedure specification


• Review the second specification (Reports.GetProductsAndModels)in the supporting documentation.

f Task 4: Design, create and test the Reports.GetProductsAndModels stored procedure


• Design, create and test the stored procedure based on the second specifications given in the
supporting documentation for the exercise.

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

Exercise 2: Create a Parameterized Stored Procedure


Scenario
In this exercise, you will create another stored procedure that takes parameters.

The main tasks for this exercise are as follows:


1. Review the Reports.GetProductsByColor stored procedure specification.
2. Design, create and test the Reports.GetProductsByColor stored procedure.

f Task 1: Review the Reports.GetProductsByColor stored procedure specification


• Review the Reports.GetProductsByColor specification in the supporting documentation.

f Task 2: Design, create and test the Reports.GetProductsByColor stored procedure


• Design, create and test the Reports.GetProductsByColor stored procedure based on the specifications
given in the supporting documentation for the exercise.

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.

Challenge Exercise 3: Alter the Execution Context of Stored Procedures


(Only if time permits)
Scenario
In this exercise, you will alter the stored procedures to use a different execution context.

The main tasks for this exercise are as follows:


1. Alter the Reports.GetProductColors stored procedure to execute as OWNER.
2. Alter the Reports.GetProductsAndModels stored procedure to execute as OWNER.
3. Alter the Reports.GetProductsByColor stored procedure to execute as OWNER.

f Task 1: Alter the Reports.GetProductColors stored procedure to execute as OWNER


• Alter the Reports.GetProductColors stored procedure to execute as OWNER and test that the
procedure still works.

f Task 2: Alter the Reports.GetProductsAndModels stored procedure to execute as


OWNER
• Alter the Reports.GetProductsAndModels stored procedure to execute as OWNER and test that the
procedure still works.

f Task 3: Alter the Reports.GetProductsByColor stored procedure to execute as OWNER


• Alter the Reports.GetProductsByColor stored procedure to execute as OWNER and test that the
procedure still works.

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

Module Review and Takeaways

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

• Implement TABLE types

• Use TABLE types as parameters


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-3

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:

• Explain the role of the MERGE statement

• Describe how to use the WHEN MATCHED clause

• Describe how to use the WHEN NOT MATCHED BY TARGET clause

• Describe how to use the WHEN NOT MATCHED BY SOURCE clause


• Explain the role of the OUTPUT clause and $action

• Describe MERGE determinism and performance


MCT USE ONLY. STUDENT USE PROHIBITED
11-4 Merging Data and Passing Tables

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

Source and Target


The MERGE statement uses two table data sources. The target table is the table that is being modified and
is specified first in the MERGE statement. Any inserts, updates or deletes are applied only to the target
table.

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

• A sub-select (or derived table) with an alias

• A common table expression (CTE)

• A VALUES clause with an alias


The source and target are matched together as the result of an ON clause. This can involve one or more
columns from both tables.
MCT USE ONLY. STUDENT USE PROHIBITED
11-6 Merging Data and Passing Tables

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:

WHEN MATCHED AND s.Quantity > 0


...
WHEN MATCHED
...

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

WHEN NOT MATCHED BY TARGET

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.

WHEN NOT MATCHED


The next clause in the MERGE statement that you will consider is the WHEN NOT MATCHED BY TARGET
statement. It was mentioned in the last topic that the most common action performed by a WHEN
MATCHED clause is to update the existing row in the target table. The most common action performed by
a WHEN NOT MATCHED BY TARGET clause is to insert a new row into the target table.

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

WHEN NOT MATCHED BY SOURCE

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.

WHEN NOT MATCHED BY SOURCE


While less commonly used than the clauses discussed in the previous topics, you can also take an action
for rows in the target that did not match any incoming rows from the source. Generally, this will involve
deleting the unmatched rows in the target table but UPDATE actions are also permitted.

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

OUTPUT Clause and $action

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:

DELETE FROM HumanResources.Employee


OUTPUT deleted.BusinessEntityID, deleted.NationalIDNumber
WHERE ModifiedDate < DATEADD(YEAR,-10,SYSDATETIME());

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:

DELETE FROM HumanResources.Employee


OUTPUT deleted.BusinessEntityID, deleted.NationalIDNumber
INTO Audit.EmployeeDelete
WHERE ModifiedDate < DATEADD(YEAR,-10,SYSDATETIME());

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

OUTPUT and MERGE


The OUTPUT clause can also be used with the MERGE statement. When an INSERT is performed, rows can
be returned from the inserted virtual table. When a DELETE is performed, rows can be returned from the
deleted virtual table. When an UPDATE is performed, values will be available in both the inserted and
deleted virtual tables.

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:

INSERT INTO Audit.EmployeeDelete


SELECT Mods.EmployeeID
FROM (MERGE INTO dbo.Employee AS e
USING dbo.EmployeeUpdate AS eu
ON e.EmployeeID = eu.EmployeeID
WHEN MATCHED THEN
UPDATE SET e.FullName = eu.FullName,
e.EmploymentStatus = eu.EmploymentStatus
WHEN NOT MATCHED THEN
INSERT (EmployeeID,FullName,EmploymentStatus)
VALUES
(eu.EmployeeID,eu.FullName,eu.EmploymentStatus)
OUTPUT $action AS Action,deleted.EmployeeID) AS Mods
WHERE Mods.Action = 'DELETE';

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.

Question: How could the OUTPUT clause be useful in a DELETE statement?


MCT USE ONLY. STUDENT USE PROHIBITED
11-12 Merging Data and Passing Tables

MERGE Determinism and Performance

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 1A: Updating Data by Using the MERGE 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_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.

4. Open the 11 – Demonstration 1A.sql script file.

5. Follow the instructions contained within the comments of the script file.

Question: What is meant by the term “composable query”?


MCT USE ONLY. STUDENT USE PROHIBITED
11-14 Merging Data and Passing Tables

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

• Describe previous options for passing lists as parameters

• Explain the role of the TABLE type

• Populate TABLE types with row constructors


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-15

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

Causes of Excessive Round Trips


Developers often aim to create code that can be reused. One common end result of this is the creation of
many small functions and procedures that perform single tasks. Performing a larger task however, can
then require calling many subtasks.

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

Options for Passing Lists as Parameters

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.

• Custom string parsing logic needed to be written.

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 2A: Passing Delimited Lists

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_11_PRJ\10776A_11_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: What are the basic problems with using delimited lists for parameters?
MCT USE ONLY. STUDENT USE PROHIBITED
11-18 Merging Data and Passing Tables

Introduction to the TABLE Type

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:

DECLARE @BalanceList TABLE (CustomerID int,


CurrentBalance decimal(18,2));

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:

CREATE TYPE dbo.CustomerBalance


AS TABLE (CustomerID int,
CurrentBalance decimal(18,2));
GO

DECLARE @BalanceList dbo.CustomerBalance;


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-19

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

Populating TABLE Types with Row Constructors

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.

Row Constructors for Populating TABLE Types


Versions of SQL Server prior to SQL Server 2008 only permitted inserting a single row of data at a time
with an INSERT statement unless an INSERT…SELECT or INSERT...EXEC statement was used. SQL Server
2008 introduced the concept of a row constructor.

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 2B: Using TABLE Types and Row Constructors

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_11_PRJ\10776A_11_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 22 – Demonstration 2B.sql script file.

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

• Use row constructors to populate parameters to be passed to stored procedures


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 11-23

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

Table Valued Parameters


Table-valued parameters can only be used as input parameters. Note that the term READONLY must be
specified and that it is the only allowable value.

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.

Reducing Round Trips


In an earlier discussion, the requirements for saving a customer order were noted. Using this same
technique, you could place the order header in one table and all the order rows in another table before
passing both in a single call to a stored procedure that saves the order. That single stored procedure
could also begin and commit the transaction so the transaction would not span even a single network
round trip.

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

Using Row Constructors to Populate Parameters

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.

Passing a Table Valued Parameter in an EXEC Statement


In addition to defining a table-valued parameter for a stored procedure, you also need to construct a
table to pass to the stored procedure in the EXEC call.

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 3A: Passing Tables to 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_11_PRJ\10776A_11_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.

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 11: Passing Tables and Merging Data

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

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


6. In the Open Project window, open the project
D:\10776A_Labs\10776A_11_PRJ\10776A_11_PRJ.ssmssln.

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

Procedure Required: Marketing.SalespersonMerge

Requirements

Input Parameters: Table of Salesperson details, including SalespersonID, FirstName, MiddleName,


LastName, BadgeNumber, EmailAlias, SalesTerritoryID. The parameter should
be named: SalespersonDetails

Output Parameters: None

Output Rows: For each row, return one column called Action that contains INSERT or
UPDATE and another column with the SalespersonID.

Notes: The SalespersonID must be provided. If it matches an existing salesperson, that


row should be updated. Only update columns that are provided. Any
SalesTerritoryID that is provided must be valid as it is defined as a foreign key
to the Marketing.SalesTerritory table.

Exercise 1: Create a TABLE Type


Scenario
In this exercise, you will create a TABLE type to support the parameter that will later need to be passed to
the replacement stored procedure.

The main tasks for this exercise are as follows:


1. Review the parameters of a stored procedure.

2. Review the existing function.

3. Create a new table type.

f Task 1: Review the parameters of a stored procedure


• Review the parameters of the existing stored procedure Reports.GetProductsByColorList.

f Task 2: Review the existing function


• Review the function dbo.StringListToTable used by the existing stored procedure. Note the hard-
coded length of 1000 for each component of the returned table entries.

f Task 3: Create a new TABLE type


• Create a new TABLE type to support this type of input parameter. Call the type StringList.

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

Exercise 2: Use a TABLE Type Parameter


Scenario
In this exercise, you will create a replacement stored procedure Reports.GetProductsByColorList_Test that
uses the TABLE type for its parameter.

The main tasks for this exercise are as follows:

1. Create the stored procedure.

2. Test the stored procedure.

f Task 1: Create the stored procedure


• Create a new stored procedure that is functionally equivalent to Reports.GetProductsByColorList
except that the new procedure (call it Reports.GetProductsByColorList_Test) takes a single table
@ColorList as a parameter.

f Task 2: Test the new procedure


• Test the new procedure.

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.

The main tasks for this exercise are as follows:

1. Create a new TABLE type.

2. Create a replacement procedure.

3. Test the replacement procedure.

f Task 1: Create a new TABLE type


• Create the required TABLE type. (Create it in the dbo schema.)

f Task 2: Create a replacement stored procedure


• Review the supporting documentation and create a replacement procedure based on the
requirements.

f Task 3: Test the replacement procedure


• Test the replacement procedure.

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

Module Review and Takeaways

Review Questions
1. What is the difference between SOURCE NOT MATCHED and TARGET NOT MATCHED in a MERGE
statement?

2. What is a key advantage of the MERGE statement in terms of performance?

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.

2. Consider making multiple-entity procedures instead of single-entity procedures to help minimize


round trip behavior and to reduce locking. For example, very minor changes are required to construct
a stored procedure that can insert multiple sales orders compared to a stored procedure that can
insert a single sales order.
MCT USE ONLY. STUDENT USE PROHIBITED
12-1

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:

• Design and implement scalar functions


• Design and implement table-valued functions

• Describe implementation considerations for functions

• Describe alternatives to functions


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-3

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.

This lesson provides an overview of functions and describes system functions.

Objectives
After completing this lesson, you will be able to:

• Describe different types of functions

• Use system functions


MCT USE ONLY. STUDENT USE PROHIBITED
12-4 Designing and Implementing User-Defined Functions

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

Inline Table-valued Functions


An inline table-valued function returns a table that is the result of a single SELECT statement. While this is
similar to a view, an inline table-valued function is more flexible in that parameters can be passed to the
SELECT statement within the function.

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

Multi-statement Table-valued Functions


A multi-statement table-valued function returns a table built by one or more Transact-SQL statements
and is similar to a stored procedure. Multi-statement table-valued functions are created for the same
reasons as inline table-valued functions, but are used when the logic that the function needs to
implement is too complex to be expressed in a single SELECT statement. They can be called from within a
FROM clause.

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.

Question: How have you used functions in other programming languages?


MCT USE ONLY. STUDENT USE PROHIBITED
12-6 Designing and Implementing User-Defined Functions

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:

• Explain a scalar function

• Create scalar functions

• Describe data type limitations

• Explain deterministic and non-deterministic functions


MCT USE ONLY. STUDENT USE PROHIBITED
12-8 Designing and Implementing User-Defined Functions

What Is a Scalar Function?

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.

For example, consider the following function definition:

CREATE FUNCTION dbo.ExtractProtocolFromURL


( @URL nvarchar(1000))
RETURNS nvarchar(1000)
AS BEGIN
RETURN CASE WHEN CHARINDEX(N':',@URL,1) >= 1
THEN SUBSTRING(@URL,1,CHARINDEX(N':',@URL,1) - 1)
END;
END;

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

Creating Scalar Functions

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.

Scalar User-defined Functions


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. The body of the function, defined in a BEGIN…END block,
contains the series of Transact-SQL statements that return the value.

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

Deterministic and Non-deterministic 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:

CREATE FUNCTION dbo.AddInteger


(@FirstValue int, @SecondValue int)
RETURNS int
AS BEGIN
RETURN @FirstValue + @SecondValue;
END;
GO

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.

Consider the following function:

CREATE FUNCTION dbo.CurrentUTCTimeAsString()


RETURNS varchar(40)
AS BEGIN
RETURN CONVERT(varchar(40),SYSUTCDATETIME(),100);
END;

Each time the function is called, it would return a different value, even though no input parameters are
supplied.

The OBJECTPROPERTY() function can be used to determine if a user-defined function is deterministic


or not.
MCT USE ONLY. STUDENT USE PROHIBITED
12-12 Designing and Implementing User-Defined Functions

Demonstration 2A: Working with Scalar Functions

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

• Describe Inline table-valued functions

• Describe multi-statement table-valued functions


MCT USE ONLY. STUDENT USE PROHIBITED
12-14 Designing and Implementing User-Defined Functions

What Are 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.

Both types of TVF can be used as the equivalent of parameterized views.


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-15

Inline Table-valued Functions

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

Multi-statement Table-valued 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 3A: Implementing Table-valued Functions

Demonstration Steps
1. If Demonstration 2A 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_12_PRJ\10776A_12_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.

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:

• Describe performance impacts of scalar functions

• Describe performance impacts of table-valued functions

• Control execution context

• Use EXECUTE AS clause


• Explain guidelines for creating functions
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 12-19

Performance Impact of Scalar Functions

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.

Common Performance Problems


The over-use of scalar functions is a common cause of performance problems in SQL Server systems. For
example, a WHERE clause predicate that calls a scalar function calls that function for every target row.

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

Performance Impact of Table-valued 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.

Common Performance Problems


Multi-statement TVFs are not incorporated into the code of the query that uses them. The inappropriate
usage of such TVFs is a common cause of performance issues in SQL Server.

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

Controlling Execution Context

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

The EXECUTE AS Clause

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

Guidelines for Creating Functions

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:

WHERE Function(CustomerID) = Value

is likely to remove the usefulness of an index on CustomerID.

• 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 4A: Controlling Execution Context

Demonstration Steps
1. If Demonstration 2A 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_12_PRJ\10776A_12_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 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:

• Compare table-valued functions and stored procedures


• Compare inline functions and views
MCT USE ONLY. STUDENT USE PROHIBITED
12-26 Designing and Implementing User-Defined Functions

Comparing Table-valued Functions and Stored Procedures

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.

For example, you cannot execute the following code:

SELECT * FROM (EXEC dbo.GetCriticalPathNodes);

The output of a function could be assigned to a variable in code.

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

Comparing Table-valued Functions and Views

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 12: 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.

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

7. In the Open Project window, open the project


D:\10776A_Labs\10776A_12_PRJ\10776A_12_PRJ.ssmssln.

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

• Phone numbers that contain 8 digits should be formatted as: XXXX-XXXX

• Phone numbers that contain 7 digits should be formatted as: XXX-XXXX

• Phone numbers that contain 6 digits should be formatted as: XXX-XXX

• All other characters should be stripped out


• Phone numbers that have different numbers of digits should have only the digits returned ie: (9234)
2345-2342 should be returned as 923423452342.
Requirements: Comma-Delimited List Function
You need to create another version of this function called dbo.IntegerListToTable that takes a comma-
delimited list of integers and returns a similar table. You need to design, implement and test the function.
You can assume that all integers sent to the function will be eight digits or less in length.
Problematic Query

SELECT dbo.JoinNames(FirstName,MiddleName,LastName) AS FullName


FROM Marketing.Prospect
ORDER BY FullName;

Exercise 1: Formatting Phone Numbers


Scenario
Your manager has noticed that phone numbers that are entered into the database tend to be formatted
in different ways by different users. She has asked you to create a function that will be used to format the
phone numbers. You need to design, implement and test the function.
The main tasks for this exercise are as follows:
1. Review the requirements.
2. Design and create the function.
3. Test the function.

f Task 1: Review the design requirements


• Review the Function Specifications: Phone Number in the supporting documentation.
MCT USE ONLY. STUDENT USE PROHIBITED
12-30 Designing and Implementing User-Defined Functions

f Task 2: Design and create the function


• Design and create the function for reformatting phone numbers.

f Task 3: Test the function


• Execute the FormatPhoneNumber function to ensure function correctly formats the phone number.

Results: After this exercise, you should have created a new FormatPhoneNumber function within the
dbo schema.

Exercise 2: Modifying an Existing Function


Scenario
An existing function dbo.StringListToTable takes a comma-delimited list of strings and returns a table. In
some application code, this causes issues with data types as the list often contains integers rather than just
simple strings.
The main tasks for this exercise are as follows:
1. Review the requirements.
2. Design and create the function.
3. Test the function.
4. Test the function with an alternate delimiter such as the pipe | character.

f Task 1: Review the requirements


• Review the requirement for the dbo.IntegerListToTable function in the Supporting Documentation.

f Task 2: Design and create the function


• Design and create the dbo.IntegerListToTable function.

f Task 3: Test the function


• Execute the dbo.IntegerListToTable function to ensure it returns the correct results.

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

Challenge Exercise 3: Resolve a Function-related Performance Issue (Only if


time permits)
Scenario
The operations team manager has approached you about a query that is performing badly. You need to
investigate it and suggest changes that might improve its performance.
The main tasks for this exercise are as follows:
1. Review the query.
2. Design an alternate query.
3. Use SET STATISTICS TIME ON to compare the performance of the new and old queries.

f Task 1: Review the query


• Review the problematic query in the Supporting Documentation.

f Task 2: Design an alternate query


• Design the query.

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

Module Review and Takeaways

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:

• Describe the role of transactions

• Explain the role of locks


• Manage locking

• Work with transaction isolation levels


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-3

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

• Describe auto commit transactions

• Describe explicit transactions


• Describe implicit transactions

• Explain the role of transaction recovery

• Detail considerations for using transactions


MCT USE ONLY. STUDENT USE PROHIBITED
13-4 Creating Highly Concurrent SQL Server 2012 Applications

What Are Transactions?

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

Auto Commit Transactions

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.

Question: When might autocommit mode not be appropriate in a database application?


MCT USE ONLY. STUDENT USE PROHIBITED
13-8 Creating Highly Concurrent SQL Server 2012 Applications

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.

XACT_ABORT has an effect on explicit transaction as well as on implicit transactions.

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.

Rolling Back a Transaction


You can cancel the work contained in a transaction by issuing the ROLLBACK TRANSACTION statement.
Use this to end a transaction if errors have occurred and you want the changes made by the transaction
to be undone and the database to return to the state it was before the transaction began.

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.

Question: When might you want to use a savepoint?


MCT USE ONLY. STUDENT USE PROHIBITED
13-10 Creating Highly Concurrent SQL Server 2012 Applications

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.

Setting Implicit Transaction Mode


You use the SET statement to switch implicit transaction mode on and off, as shown in the following
example:

SET IMPLICIT_TRANSACTIONS ON;


-- Do some work in implicit transaction mode.
SET IMPLICIT TRANSACTIONS OFF;
-- Return to autocommit mode.

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

Starting Implicit Transactions


When using implicit transaction mode, a transaction is automatically started when any of the following
statements that are shown on the slide are executed.

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.

Ending Implicit Transactions


If you do not explicitly end an implicit transaction, none of the changes will be committed to the database
when the user disconnects. You must use the COMMIT TRANSACTION statement to make the changes
permanent or the ROLLBACK TRANSACTION statement to delete the changes and release any locks that
are being held.

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

System Failures and Restarts


The recovery process runs automatically every time that SQL Server starts, such as after an intended
shutdown or a power failure. The automatic recovery process uses the transaction log to roll forward any
committed transactions and roll back any incomplete transactions. The log uses the last checkpoint as a
starting marker knowing that all transactions committed before this were written to the database and that
all transactions that started before this, but were still active, need to be rolled back as the changes were
already written to the data files.

In the slide example:


• Transaction 1 is committed before the checkpoint, so it is reflected in the database.

• 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

Considerations for Using Transactions

Key Points
There are a number of general considerations that need to be kept in mind when working with
transactions.

Keep Transactions As Short As Possible


Transactions should be as short as possible. Longer transactions increase the likelihood that users will not
be able to access locked data. Some methods to keep transactions short include the following:

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

Try To Access Resources in the Same Order


Accessing resources in the same order within transactions tends to naturally serialize your access to the
database and can help to avoid deadlocks. However, doing this is not always possible.

Note that deadlocks will be discussed later in the module.


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-15

Considerations for Nested Transactions


Consider the following issues regarding nested transactions:

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

Question: When would nested transactions be appropriate?


MCT USE ONLY. STUDENT USE PROHIBITED
13-16 Creating Highly Concurrent SQL Server 2012 Applications

Demonstration 1A: Working with Transactions

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.

4. Open the 11 – Demonstration 1A.sql script file.

5. Open the 12 – Demonstration 1A 2nd Window.sql script file.

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

• Explain what locks are

• Differentiate between blocking and locking


• Describe what concurrency problems are prevented by locking

• Detail SQL Server's lockable resources

• Describe the types of locks that are available

• Explain lock compatibility


MCT USE ONLY. STUDENT USE PROHIBITED
13-18 Creating Highly Concurrent SQL Server 2012 Applications

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.

Pessimistic Concurrency Control


Pessimistic concurrency control locks data when data is read in preparation for an update. Other users
cannot then perform actions that would alter the underlying data until the user who applied the lock is
done with the data.

Optimistic Concurrency Control


Optimistic concurrency control does not hold locks on data after the data is initially read. Rather, when an
update is performed, SQL Server checks to determine whether the underlying data was changed since it
initially read it. If so, the user receives an error, the transaction rolls back, and the user must start over.
Optimistic concurrency control works well where a low level of contention for data exists.

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

What Are Locks?

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

Blocking vs. Locking

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

What Concurrency Problems Are Prevented by Locking?

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.

Consider the following facts about shared locks:


• They are used for read-only operations; data cannot be modified.
• SQL Server releases shared locks on a record as soon as the next record is read.
• A shared lock will exist until all rows that satisfy the query have been returned to the client.
• Exclusive locks. SQL Server uses exclusive (write) locks for the INSERT, UPDATE, and DELETE data
modification statements.

Consider the following facts about exclusive locks:


• Only one transaction can acquire an exclusive lock on a resource.
• A transaction cannot acquire a shared lock on a resource that has an exclusive lock.
• A transaction cannot acquire an exclusive lock on a resource until all shared locks are released.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-25

Special Situation Locks


Depending on the situation, SQL Server can use other types of locks:

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

SQL Server provides two types of schema locks:


• Schema stability (Sch-S), which ensures that a resource is not dropped.
• Schema modification (Sch-M), which ensures that other sessions do not reference a resource that
is under modification.
• Bulk update locks. SQL Server uses these to enable processes to bulk copy data concurrently into the
same table while preventing other processes that are not bulk-copying data from accessing the table.
SQL Server uses bulk update locks when either of the following is used: the TABLOCK hint or the table
lock on bulk load option.

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

Existing granted lock

Requested Lock IS S U IX SIX X

Intent shared (IS) Yes Yes Yes Yes Yes No

Shared (S) Yes Yes Yes No No No

Update (U) Yes Yes No No No No

Intent exclusive (IX) Yes No No Yes No No

Shared with intent exclusive (SIX) Yes No No No No No

Exclusive (X) No No No No No No
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-27

In addition, compatibility for schema locks is as follows:


• The schema modification lock (Sch-M) is incompatible with all locks.
• The schema stability lock (Sch-S) is compatible with all locks except the schema modification
lock (Sch-M).

Question: Can you think of situations where lock compatibility is important?


MCT USE ONLY. STUDENT USE PROHIBITED
13-28 Creating Highly Concurrent SQL Server 2012 Applications

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:

• Explain locking timeout


• Describe lock escalation

• Explain what deadlocks are

• Describe locking-related table hints


• Describe methods to view locking information
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-29

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.

SQL Server Lock Escalation


As the SQL Server Database Engine acquires low-level locks, it also places intent locks on the objects that
contain the lower-level objects.

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:

• Leaf-level pages of nonclustered indexes

• Data pages of clustered indexes

• Heap data pages

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.

Lock escalation behavior can be changed by the ALTER TABLE statement.

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

What Are Deadlocks?

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 holds a shared lock on row 1.

• Transaction B holds a shared lock on row 2.

• 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

How SQL Server Ends a Deadlock


SQL Server ends a deadlock by automatically terminating one of the transactions. The process SQL Server
uses is in the following list.

• Rolls back the transaction of the deadlock victim

• In a deadlock, SQL Server chooses as the deadlock victim the session running the transaction that
is the least expensive to roll back.

• Notifies the deadlock victim’s application (with message number 1205)

• Cancels the deadlock victim’s current request

• Allows other transactions to continue

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

Locking-related Table Hints

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.

Question: Why would you ever take an exclusive table-lock?


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-35

Methods to View Locking Information

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.

Dynamic Management Views


Many DMVs are available for viewing locking information. Amongst the more useful are:

Dynamic Management View

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

SQL Server Profiler and Extended Events Profiler


SQL Server Profiler is a standalone tool that monitors server activities. Extended Events Profiler is a similar
tool that is part of SQL Server Management Studio. You can collect information about a variety of events
by creating traces in SQL Server Profiler or sessions in Extended Events Profiler. Both provide a detailed
insight into server events. These details can be used to analyze and resolve server resource issues, monitor
login attempts and connections, and correct deadlock problems.

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.

Reliability and Performance Monitor


You can view SQL Server locking information by using Reliability and Performance Monitor in Microsoft
Windows®. Use the SQLServer:Locks objects to retrieve this information.

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 3A: Viewing Locking Information

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_13_PRJ\10776A_13_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. Open the 32 – Demonstration 3A 2nd Window.sql script file.


4. Open the 33 – Demonstration 3A 3rd Window.sql script file.

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:

• Describe SQL Server transaction isolation levels

• Explain the role of the read committed snapshot database option

• Detail isolation-related table hints


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 13-39

SQL Server Transaction Isolation Levels

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.

Transaction Isolation Levels


Setting transaction isolation levels allows programmers to accept increased risk of integrity problems in
exchange for greater concurrent access to data. The higher the isolation level, the lower the risk of data
integrity problems. This is at the cost of locks being held for longer, and the locks themselves being more
restrictive with respect to concurrent transactions.
You can override a session-level isolation level in individual statements by using lock specification. You
can set the transaction isolation level for a session by using the SET statement.

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

Read Committed Snapshot

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.

Read Committed Snapshot


Read Committed Snapshot is a database option that, when enabled, causes DML statements to start
generating row versions, even when no transaction is using snapshot isolation. Transactions that specify
read committed are automatically altered to use row versioning rather than locking. All statements see a
snapshot of data as it existed at the start of the statement.
The behavior of the READ COMMITTED transaction isolation level depends on the setting of the
READ_COMMITTED_SNAPSHOT database option, which can be ON or OFF.

The following table describes the locking isolation level options:

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

Isolation-related Table Hints

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.

Isolation-related Table Hints


Similar to the locking hints, these should in general be avoided. However, they do provide a way to
override the default behavior on an individual table basis within a statement. This could be useful in
specialized situations.
MCT USE ONLY. STUDENT USE PROHIBITED
13-44 Creating Highly Concurrent SQL Server 2012 Applications

Lab 13: Creating Highly Concurrent SQL Server


Applications

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

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

6. In the Open Project window, open the project


D:\10776A_Labs\10776A_13_PRJ\10776A_13_PRJ.ssmssln.

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

Exercise 1: Detecting Deadlocks


Scenario
In this exercise, you will explore typical causes of deadlocks and learn to view them in SQL Server
Profiler traces.
The main tasks for this exercise are as follows:
1. Start and configure SQL Server Profiler.

2. Load and execute the test scripts.

3. Stop the trace and review the deadlock graph.

f Task 1: Start and configure SQL Server Profiler


• Start SQL Server Profiler and create a new trace called Deadlock Detection.
• Add Deadlock Graph to the events.
• Remove all other events.
• Start the trace in Profiler.

f Task 2: Load and execute the test scripts


• Open the 51 – Lab Exercise 1.sql script.
• Review the script.
• Open the 52 – Lab Exercise 1 second Window.sql script.
• Review the script.
• Execute 51 – Lab Exercise 1.sql and then immediately execute 52 – Lab Exercise 1 second Window.sql.
Wait for both to complete.

f Task 3: Stop the trace and review the deadlock graph


• Stop the trace.
• Review the deadlock graph.

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

Challenge Exercise 2: Investigating Transaction Isolation Levels (Only if


time permits)
Scenario
In this exercise, you will execute a supplied set of T-SQL scripts that demonstrate how different transaction
isolation levels work.
The main tasks for this exercise are as follows:
1. Load the scripts.

2. Execute the code.

f Task 1: Load the scripts


• Open the 62 – Lab Exercise 2 second Window.sql script.
• Open the 61 – Lab Exercise 2.sql script.

f Task 2: Execute the code


• Execute the code step by step, making sure to highlight and execute just the required code blocks in
each script window, by following the step by step instructions.

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

Module Review and Takeaways

Review Questions
1. Why is snapshot isolation level helpful?

2. What is the difference between a shared lock and an exclusive lock?


3. Why would you use read committed snapshot rather than snapshot isolation level?

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:

• Design T-SQL error handling


• Implement T-SQL error handling

• Implement structured exception handling


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-3

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

• Describe types of errors

• Explain what values are returned by an error


• Describe different levels of error severities
MCT USE ONLY. STUDENT USE PROHIBITED
14-4 Handling Errors in T-SQL Code

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:

SELECT * FROM Custommer;

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:

SELECT TOP(10) FROM Production.Product;

If you try to execute the statement, you receive the following message:

Msg 156, Level 15, State 1, Line 1


Incorrect syntax near the keyword 'FROM'.

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.

Object Resolution Errors


In the last topic, you saw an example of an object resolution error. These errors occur when the object
name specified cannot be resolved to an object ID, such as in the following statement:

SELECT * FROM SomeNonexistentTable;

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

Statement Terminating Errors


With a statement terminating error, execution resumes at the next statement following the statement that
was in error. Consider the following batch executed against the AdventureWorks database:

DELETE FROM Production.Product WHERE ProductID = 1;


PRINT 'Hello';

When this batch is executed, the following is returned:

Msg 547, Level 16, State 0, Line 3

The DELETE statement conflicted with the REFERENCE constraint


"FK_BillOfMaterials_Product_ComponentID". The conflict occurred in database
"AdventureWorks", table "Production.BillOfMaterials", column 'ComponentID'.
The statement has been terminated.
Hello

From the example you can see that the PRINT statement was still executed even though the DELETE
statement failed because of a constraint violation.

Batch, Scope, Session and Server Terminating Errors


More serious errors can cause the batch, the scope (eg: the current stored procedure) or the session to be
terminated.

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:

SELECT * FROM sys.messages


ORDER BY message_id, language_id;

When executed, this command returns the following:

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.

Question: Why is it useful to be able to localize error messages?


MCT USE ONLY. STUDENT USE PROHIBITED
14-10 Handling Errors in T-SQL Code

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:

SELECT COUNT(Color) FROM Production.Product;

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:

Warning: Null value is eliminated by an aggregate or other SET operation.

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

Severity 10 is the top of the informational messages.


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-11

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.

Here are a few examples of these errors:

Error Severity Example

11 indicates that an object does not exist

13 indicates a transaction deadlock

14 indicates errors such as permission denied

15 indicates syntax errors

16 indicates general errors that can be corrected by the user

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 1A: Working with Error Types and Severity

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.

4. Open the 11 – Demonstration 1A.sql script file.

5. Follow the instructions contained within the comments of the script file.

Question: What do you imagine the “is_event_logged” column relates to?


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-13

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

• Raise errors using the RAISERROR statement

• Raise errors using the THROW statement

• Use the @@ERROR system variable

• Explain transaction nesting errors

• Raise custom errors

• Create alerts that fire when errors occur


MCT USE ONLY. STUDENT USE PROHIBITED
14-14 Handling Errors in T-SQL Code

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.

Statement Terminating Errors vs Batch/Scope Terminating Errors


Most common errors that occur when processing T-SQL are statement terminating errors not batch
or scope terminating errors. This means that the statement in error is rolled back and execution then
continues with the next statement following the statement in error. Note that this happens even when
working within a transaction.
For example, consider the following code:

BEGIN TRAN;

DELETE Production.Product WHERE ProductID = 1;


PRINT 'Hello';

COMMIT;

PRINT 'Hello again';


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-15

Note that when it is executed, the following output is generated:

Msg 547, Level 16, State 0, Line 3


The DELETE statement conflicted with the REFERENCE constraint
"FK_BillOfMaterials_Product_ComponentID". The conflict occurred in database
"AdventureWorks", table "Production.BillOfMaterials", column 'ComponentID'.
The statement has been terminated.
Hello
Hello again

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.

Now consider the same code with SET XACT_ABORT ON present:

SET XACT_ABORT ON;

BEGIN TRAN;

DELETE Production.Product WHERE ProductID = 1;


PRINT 'Hello';

COMMIT;

PRINT 'Hello again';

When executed, it returns:

Msg 547, Level 16, State 0, Line 5


The DELETE statement conflicted with the REFERENCE constraint
"FK_BillOfMaterials_Product_ComponentID". The conflict occurred in database
"AdventureWorks", table "Production.BillOfMaterials", column 'ComponentID'.

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

Raising Errors Using RAISERROR

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:

• Help troubleshoot T-SQL code

• Check the values of data

• Return messages that contain variable text


Note that using a PRINT statement is similar to raising an error of severity 10, as shown in the sample on
the slide.

Substitution Placeholders and Message Number


Note that in the message shown in the example on the slide, that %d is a placeholder for a number and
%s is a placeholder for a string. Note also that a message number was not mentioned. When errors with
message strings are raised using this syntax, the errors raised always have error number 50000.

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

Raising Errors Using THROW

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 are always severity 16


• The messages returned by THROW are not related to any entries in sys.sysmessages

• 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:

RAISERROR(N'Message', 16, 1);


IF @@ERROR <> 0
PRINT 'Error=' + CAST(@@ERROR AS VARCHAR(8));
GO

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:

Msg 50000, Level 16, State 1, Line 1


Message
Error=0

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

Capturing @@ERROR into a Variable


For this reason, when working with @@ERROR, it is important to capture the error number into a variable
as soon as it is raised and to then continue processing with the variable.

Look at the following code that demonstrates this:

DECLARE @ErrorValue int;


RAISERROR(N'Message', 16, 1);
SET @ErrorValue = @@ERROR;
IF @ErrorValue <> 0
PRINT 'Error=' + CAST(@ErrorValue AS VARCHAR(8));

When this code is executed, it returns the following output:

Msg 50000, Level 16, State 1, Line 2


Message
Error=50000

Note that the error number is correctly reported now.

Centralizing Error Handling


One other significant issue with using @@ERROR for error handling is that it is difficult to centralize error
handling within your T-SQL code. Error handling tends to end up scattered throughout the code. It would
be possible to somewhat centralized error handling using @@ERROR by using labels and GOTO
statements but this would be frowned upon by most developers today as a poor coding practice.
MCT USE ONLY. STUDENT USE PROHIBITED
14-20 Handling Errors in T-SQL Code

Transaction Nesting Errors

Key Points
Any ROLLBACK causes all levels of transactions to be rolled back, not just the current nesting level.

Transaction Nesting Errors


SQL Server does not support nested transactions. The syntax of the language might appear to support
them but they do not operate in a nested fashion.

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

Raising Custom Errors

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.

Raising Custom Errors


As well as being able to define custom error messages, members of the sysadmin server role can also use
an additional parameter @with_log. When set to TRUE, the error will also be recorded in the Windows
Application log. Any message written to the Windows Application log is also written to the SQL Server
error log. Be judicious with the use of the @with_log option as network and system administrators tend to
dislike applications that are “chatty” in the system logs. However, if the error needs to be trapped by an
Alert, the error must first be written to the Windows Application log.
Note that raising system errors is not supported.

sys.messages System View


The messages that are added are visible within the sys.messages system view along with the system-
supplied error messages. Messages can be replaced without the need to delete them first by using the
@replace = ‘replace’ option.
The messages are customizable and different messages can be added for the same error number for
multiple languages, based on a language_id value. (Note: English messages are language_id 1033.)

Question: What do the DB_ID and DB_NAME functions return?


MCT USE ONLY. STUDENT USE PROHIBITED
14-22 Handling Errors in T-SQL Code

Creating Alerts When Errors Occur

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 2A: Handling Errors Using T-SQL

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_14_PRJ\10776A_14_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. Open the 22 – Demonstration 2A 2nd Window.sql script file.


4. Follow the instructions contained within the comments of the script file.

Question: Why is the ability to substitute values in error messages useful?


MCT USE ONLY. STUDENT USE PROHIBITED
14-24 Handling Errors in T-SQL Code

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

• Describe the role of error handling functions

• Describe catchable vs non-catchable errors


• Explain how TRY CATCH relates to transactions

• Explain how errors in managed code are surfaced


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 14-25

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.

TRY/CATCH Block Programming


Structured exception handling is more powerful than error handling based on the @@ERROR system
variable. It allows you to prevent code from being littered with error handling code and to centralize that
error handling code.

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.

TRY Block and CATCH Block


When using structured exception handling, code that might raise an error is placed within a TRY block.
TRY blocks are enclosed by BEGIN TRY and END TRY statements.

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

Error Handling Functions

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.

Error Handling Functions


Recall that when programming with @@ERROR, the value held by the @@ERROR system variable was
reset as soon as the next statement was executed.

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

Catchable vs. Non-catchable Errors

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.

Catchable vs Non-catchable Errors


Not all errors can be caught by TRY/CATCH blocks within the same scope that the TRY/CATCH block exists
in. Often the errors that cannot be caught in the same scope can be caught in a surrounding scope. For
example, you might not be able to catch an error within the stored procedure that contains the
TRY/CATCH block, however you are likely to be able to catch that error in a TRY/CATCH block in the code
that called the stored procedure where the error occurred.

Common Non-catchable Errors


Common examples of non-catchable errors are:

• 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

Rethrowing Errors Using THROW

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

TRY/CATCH and Transactions

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 0 indicates that there is no active transaction.

• 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

Errors in Managed 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.

Errors in Managed Code


In general, you may wish to catch errors as much as possible within managed code. (Managed code is
discussed in Module 16.)

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 3A: Applying Retry Logic to Deadlocks

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_14_PRJ\10776A_14_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. Open the 32 – Demonstration 3A 2nd Window.sql script file.


4. Follow the instructions contained within the comments of the script file.
MCT USE ONLY. STUDENT USE PROHIBITED
14-32 Handling Errors in T-SQL Code

Lab 14: Handling Errors in T-SQL Code

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

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


6. In the Open Project window, open the project
D:\10776A_Labs\10776A_14_PRJ\10776A_14_PRJ.ssmssln.

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

Exercise 1: Replace @@ERROR-based Error Handling with Structured


Exception Handling
Scenario
In this exercise, you need to modify his code to use structured exception handling.

The main tasks for this exercise are as follows:

1. Review the existing code.


2. Rewrite the stored procedure to use structured exception handling.

3. Test that the procedure.

f Task 1: Review the existing code


• Review the existing code in the procedure Marketing.MoveCampaignBalance.

f Task 2: Rewrite the stored procedure to use structured exception handling


• Rewrite the stored procedure to use structured exception handling, calling the rewritten stored
procedure Marketing.MoveCampaignBalance_Test.

f Task 3: Test the stored procedure


• Test that the stored procedure still works as expected.

Results: After this exercise, you have created a stored procedure that uses structured exception
handling.

Challenge Exercise 2: Add Deadlock Retry Logic to the Stored Procedure


(Only if time permits)
Scenario
In this exercise, the operations team have mentioned that the same stored procedure also seems to
routinely fail with deadlock errors. To assist them, make further modifications to your new procedure to
add automatic retry code for deadlock errors.
The main tasks for this exercise are as follows:

1. Modify the code to re-try on deadlock.

2. Test the stored procedure.

f Task 1: Modify the code to re-try on deadlock


• Modify the code for the Marketing.MoveCampaignBalance_Test stored procedure to re-try on
deadlock up to five times.

f Task 2: Test the stored procedure


• Test that the procedure still works as expected.

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

Module Review and Takeaways

Review Questions
1. What is the purpose of the SET XACT_ABORT ON statement?

2. Why should retry logic be applied to deadlock handling?


3. Give an example of an error that retries would not be useful for.

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

• Commit the transaction

Consider instead a pattern like:

• Reset the retry count.

• 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:

• Design DML triggers


• Implement DML triggers

• Explain advanced DML trigger concepts


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-3

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:

• Describe DML triggers

• 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

• Describe performance-related considerations for triggers


MCT USE ONLY. STUDENT USE PROHIBITED
15-4 Responding to Data Manipulation via Triggers

What Are DML Triggers?

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

Complex Logic and Meaningful Error Messages


Triggers can guard against malicious or incorrect INSERT, UPDATE, and DELETE operations and enforce
other restrictions that are more complex than those defined by using CHECK constraints. For example, a
trigger could check referential integrity for one column, only when another column holds a specific value.

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

AFTER Triggers vs. INSTEAD OF 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.

Common reasons for implementing AFTER triggers are:


• Providing auditing of the changes that were made.
• Implementing complex rules involving the relationship between tables.
• Implementing default values or calculated values within rows.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-7

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

Inserted and Deleted Virtual Tables

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.

inserted and Deleted Virtual Tables


After an INSERT operation, the inserted virtual table holds details of the rows just inserted. The underlying
table also has those rows in it. After an UPDATE operation, the inserted virtual table holds details of the
modified versions of the rows. The underlying table also has those rows in the modified form.

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.

INSTEAD OF Triggers and the Inserted and Deleted Virtual Tables


When an INSERT, DELETE, or UPDATE statement is attempted and an INSTEAD OF trigger is associated
with the event on the table, the inserted and deleted virtual tables hold details of the modifications that
need to be made but have not yet been made.

Scope of Inserted and Deleted


The inserted and deleted virtual tables are only available during the execution of the trigger code and are
scoped directly to the trigger code. This means that if the trigger code was to execute a stored procedure,
that stored procedure would not have access to the inserted and deleted virtual tables.
MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-9

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 vs. Triggers


When an AFTER trigger decides to disallow a data modification, it does so by executing a ROLLBACK
statement. This causes the entire work done by the statement to then be undone by the ROLLBACK.
Higher performance is obtained by avoiding the data modification ever occurring.

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.

RowVersions and tempdb


Since SQL Server 2005, trigger performance has been improved when compared to earlier versions. In
earlier versions, the inserted and deleted virtual tables were constructed from entries in the transaction
log. The data in these tables needed to be reconstructed when it was required. From SQL Server 2005
onwards, a special rowversion table was provided in the tempdb database. This special table holds copies
of the data in the inserted and deleted virtual tables for the duration of the trigger. This design improved
the performance of triggers but means that excessive usage of triggers could cause performance issues
within the tempdb database.
MCT USE ONLY. STUDENT USE PROHIBITED
15-12 Responding to Data Manipulation via Triggers

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:

• Implement AFTER INSERT triggers


• Implement AFTER DELETE triggers

• Implement AFTER UPDATE triggers.


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-13

AFTER INSERT Triggers

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.

AFTER INSERT Trigger Actions


When an AFTER INSERT trigger fires, new rows are added to both the base table and to the inserted
virtual table. The inserted virtual table holds a copy of the rows that have been inserted into the base
table.

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.

Question: When would you use an INSERT trigger?


MCT USE ONLY. STUDENT USE PROHIBITED
15-14 Responding to Data Manipulation via Triggers

Demonstration 2A: Working with AFTER INSERT Triggers

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.

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 15-15

AFTER DELETE Triggers

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.

AFTER DELETE Trigger Actions


When an AFTER DELETE trigger fires, rows are removed from the base table and added to the deleted
virtual table. The deleted virtual table holds a copy of the rows that have been deleted from the base
table.

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 2B: Working with AFTER DELETE Triggers

Demonstration Steps
1. If Demonstration 2A 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_15_PRJ\10776A_15_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 22 – Demonstration 2B.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 15-17

AFTER UPDATE Triggers

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.

AFTER UPDATE Trigger Actions


When an AFTER UPDATE trigger fires, update actions are treated as a set of deletions of how the rows
were and insertions of how the rows now are. Rows that are to be modified in the base table are copied to
the deleted virtual table and the updated versions of the rows are copied to the inserted virtual table. The
inserted virtual table holds a copy of the rows in their modified state, the same as how the rows appear
now in the base table.

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 2C: Working with AFTER UPDATE Triggers

Demonstration Steps
1. If Demonstration 2A 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_15_PRJ\10776A_15_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 23 – Demonstration 2C.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 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

• Explain the alternatives to using triggers


MCT USE ONLY. STUDENT USE PROHIBITED
15-20 Responding to Data Manipulation via Triggers

INSTEAD OF Triggers

Key Points
INSTEAD OF triggers cause the execution of alternate code instead of executing the statement that
caused them to fire.

INSTEAD OF vs BEFORE Triggers


Some other database engines provide BEFORE triggers. In those databases, the action in the BEFORE
trigger happens before the data modification statement which also occurs. SQL Server INSTEAD OF
triggers are different from the BEFORE triggers that you may have come across in other database engines.
It is important to realize that with an INSTEAD OF trigger as implemented in SQL Server, only the code in
the trigger is executed. The original operation that caused the trigger to fire is not executed.

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 3A: Working with INSTEAD OF Triggers

Demonstration Steps
1. If Demonstration 2A 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_15_PRJ\10776A_15_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.

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

How Nested Triggers Work

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.

Question: How might nested triggers work in an Employee database?


MCT USE ONLY. STUDENT USE PROHIBITED
10776A: Developing Microsoft® SQL Server® 2012 Databases 15-23

Considerations for Recursive Triggers

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

Trigger Firing Order

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

Alternatives to Using 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.

Constraint Use Is Not Always Possible


While general guidelines are provided here, replacing the triggers with these alternatives is not always
possible. For example, the logic required when checking values might be too complex for a CHECK
constraint.

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 3B: Replacing Triggers with Computed Columns

Demonstration Steps
1. If Demonstration 2A 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_15_PRJ\10776A_15_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 32 – Demonstration 3B.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 15-29

Lab 15: Responding to Data Manipulation via Triggers

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

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


6. In the Open Project window, open the project
D:\10776A_Labs\10776A_15_PRJ\10776A_15_PRJ.ssmssln.

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:

Column Data Type Value to Insert

CampaignAuditID int IDENTITY

AuditTime datetime2 SYSDATETIME()

ModifyingUser sysname ORIGINAL_LOGIN()

RemainingBalance decimal(18,2) RemainingBalance after update

Exercise 1: Creating and Testing the Audit Trigger


Scenario
The Marketing.CampaignBalance table includes a column called RemainingBalance. Any time an update is
made to the table, if either the existing balance or the new balance is greater than 10000, an entry needs
to be written to the audit table Marketing.CampaignAudit.

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

The main tasks for this exercise are as follows:

1. Review the supporting documentation and existing system.

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 1: Review the supporting documentation and existing system


• Review the existing structure of the Marketing.CampaignAudit table and the values required in each
column, based on the supporting documentation.
• Review the existing structure of the Marketing.CampaignBalance table.

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.

f Task 3: Write code to test the behavior of the trigger


• Execute data modification statements designed to test that the trigger is working as expected.

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

Challenge Exercise 2: Improve the Audit Trigger (Only if time permits)


Scenario
Now that the trigger that was created in Exercise 1 has been deployed to production, the operations team
is complaining that too many entries are being audited. Many accounts have more than 10000 as a
balance and minor movements of money are causing audit entries. You need to modify the trigger so that
only changes in the balance of more than 10000 are audited instead.

The main tasks for this exercise are as follows:

1. Modify the trigger based on the updated requirements.

2. Delete all rows from the Marketing.CampaignAudit table.

3. Test the modified trigger.

f Task 1: Modify the trigger based on the updated requirements


• Review the design of the existing trigger and decide what modifications need to be made to it.
• Use an ALTER TRIGGER statement to change the existing trigger so that it will meet the updated
requirements.

f Task 2: Delete all rows from the Marketing.CampaignAudit table


• Execute a DELETE statement to remove all existing rows from the Marketing.CampaignAudit table.

f Task 3: Test the modified trigger


• Execute data modification statements designed to test that the trigger is working as expected.

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

Module Review and Takeaways

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.

2. Avoid using triggers in situations where constraints could be used instead.

You might also like