100% found this document useful (2 votes)
43 views

Instant Download Expert Scripting and Automation for SQL Server DBAs 1st Edition Peter A. Carter (Auth.) PDF All Chapters

DBAs

Uploaded by

tsykeubarci
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
43 views

Instant Download Expert Scripting and Automation for SQL Server DBAs 1st Edition Peter A. Carter (Auth.) PDF All Chapters

DBAs

Uploaded by

tsykeubarci
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

Download the full version of the textbook now at textbookfull.

com

Expert Scripting and Automation for SQL


Server DBAs 1st Edition Peter A. Carter
(Auth.)

https://textbookfull.com/product/expert-scripting-
and-automation-for-sql-server-dbas-1st-edition-
peter-a-carter-auth/

Explore and download more textbook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Expert Scripting and Automation for SQL Server DBAs


Springerlink (Online Service)

https://textbookfull.com/product/expert-scripting-and-automation-for-
sql-server-dbas-springerlink-online-service/

textbookfull.com

Securing SQL Server: DBAs Defending the Database 2nd


Edition Peter A. Carter

https://textbookfull.com/product/securing-sql-server-dbas-defending-
the-database-2nd-edition-peter-a-carter/

textbookfull.com

Expert SQL Server Transactions and Locking: Concurrency


Internals for SQL Server Practitioners 1st Edition Dmitri
Korotkevitch
https://textbookfull.com/product/expert-sql-server-transactions-and-
locking-concurrency-internals-for-sql-server-practitioners-1st-
edition-dmitri-korotkevitch/
textbookfull.com

Ultrafast Dynamics Driven by Intense Light Pulses: From


Atoms to Solids, from Lasers to Intense X-rays 1st Edition
Markus Kitzler
https://textbookfull.com/product/ultrafast-dynamics-driven-by-intense-
light-pulses-from-atoms-to-solids-from-lasers-to-intense-x-rays-1st-
edition-markus-kitzler/
textbookfull.com
Designed to Move The Science Backed Program to Fight
Sitting Disease and Enjoy Lifelong Health Dr. Joan
Vernikos
https://textbookfull.com/product/designed-to-move-the-science-backed-
program-to-fight-sitting-disease-and-enjoy-lifelong-health-dr-joan-
vernikos/
textbookfull.com

Electronic Engineering: Proceedings of the 4th


International Conference of Electronic Engineering and
Information Science (ICEEIS 2017), January 7-8, 2017,
Haikou, P.R. China. 4th Edition Dongxingwang
https://textbookfull.com/product/electronic-engineering-proceedings-
of-the-4th-international-conference-of-electronic-engineering-and-
information-science-iceeis-2017-january-7-8-2017-haikou-p-r-china-4th-
edition-dongxingwang/
textbookfull.com

Group Dynamics for Teams Daniel J. Levi

https://textbookfull.com/product/group-dynamics-for-teams-daniel-j-
levi/

textbookfull.com

Cybersecurity Fundamentals: A Real-World Perspective Kutub


Thakur

https://textbookfull.com/product/cybersecurity-fundamentals-a-real-
world-perspective-kutub-thakur/

textbookfull.com

Neurocritical care 2nd Edition Fugate

https://textbookfull.com/product/neurocritical-care-2nd-edition-
fugate/

textbookfull.com
Powering Up Children The Learning Power Approach to
Primary Teaching The Learning Power series Guy Claxton

https://textbookfull.com/product/powering-up-children-the-learning-
power-approach-to-primary-teaching-the-learning-power-series-guy-
claxton/
textbookfull.com
T H E E X P E R T ’S V O I C E ® I N S Q L S E R V E R

Expert Scripting
and Automation
for SQL Server
DBAs
Amplifying your personal productivity
and impact as a database administrator

Peter A. Carter
Expert Scripting and
Automation for SQL
Server DBAs

Peter A. Carter
Expert Scripting and Automation for SQL Server DBAs
Peter A. Carter
Botley
United Kingdom
ISBN-13 (pbk): 978-1-4842-1942-3 ISBN-13 (electronic): 978-1-4842-1943-0
DOI 10.1007/978-1-4842-1943-0
Library of Congress Control Number: 2016948124
Copyright © 2016 by Peter A. Carter
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is
concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction
on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic
adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted
from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied
specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser
of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright
Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer.
Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to
prosecution under the respective Copyright Law.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every
occurrence of a trademarked name, logo, or image, we use the names, logos, and images only in an editorial fashion
and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified
as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither
the author nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may
be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Managing Director: Welmoed Spahr
Lead Editor: Jonathan Gennick
Technical Reviewer: Philip Browne
Editorial Board: Steve Anglin, Pramila Balen, Laura Berendson, Aaron Black, Louise Corrigan, Jim DeWolf,
Jonathan Gennick, Robert Hutchinson, Celestin Suresh John, James Markham, Susan McDermott,
Matthew Moodie, Natalie Pao, Ben Renow-Clarke, Gwenan Spearing
Coordinating Editor: Jill Balzano
Copy Editor: Michael G. Laraque
Compositor: SPi Global
Indexer: SPi Global
Artist: SPi Global
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street,
6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.
com, or visit www.springer.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer
Science+Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use.
eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk
Sales–eBook Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this text is available to readers at
www.apress.com. For detailed information about how to locate your book’s source code, go to
www.apress.com/source-code/.
Printed on acid-free paper
This book is dedicated to my wonderful children: Finola, Iris, and Reuben.
Contents at a Glance

About the Author ..................................................................................................... xi


About the Technical Reviewer ............................................................................... xiii
Introduction .............................................................................................................xv

■Chapter 1: T-SQL Techniques for DBAs .................................................................. 1


■Chapter 2: PowerShell Fundamentals ................................................................. 23
■Chapter 3: SQL Server Agent Multi-Server Environments ................................... 43
■Chapter 4: Metadata-Driven Automation ............................................................. 77
■Chapter 5: Automation Techniques with SSIS ................................................... 105
■Chapter 6: Building an Inventory Database ....................................................... 157
■Chapter 7: Automating Instance Builds ............................................................. 177
■Chapter 8: Driving Automation Through Monitoring ......................................... 205
■Chapter 9: Automating Routine Maintenance and Break/Fix Scenarios............ 253

Index ..................................................................................................................... 281

v
Contents

About the Author ..................................................................................................... xi


About the Technical Reviewer ............................................................................... xiii
Introduction .............................................................................................................xv

■Chapter 1: T-SQL Techniques for DBAs .................................................................. 1


Using the APPLY Operator ................................................................................................. 1
Understanding XML .......................................................................................................... 2
Converting Results Sets to XML ............................................................................................................. 4
Extracting Values from XML Documents............................................................................................... 17

Efficient Looping ............................................................................................................ 20


Summary ........................................................................................................................ 22
■Chapter 2: PowerShell Fundamentals ................................................................. 23
Getting Started with PowerShell .................................................................................... 23
PowerShell Environments..................................................................................................................... 23
Enabling Script Execution ..................................................................................................................... 26

Language Fundamentals ................................................................................................ 27


Comments ............................................................................................................................................ 27
Standards and Aliases .......................................................................................................................... 28
Data Types ............................................................................................................................................ 31
Variables ............................................................................................................................................... 31
Piping, Filtering, and Controlling Flow .................................................................................................. 33
Importing Modules................................................................................................................................ 37

vii
■ CONTENTS

sqlps Module .................................................................................................................. 38


Navigating an Instance ................................................................................................... 40
Summary ........................................................................................................................ 41
■Chapter 3: SQL Server Agent Multi-Server Environments ................................... 43
Using Central Management Servers............................................................................... 43
Registering a Central Management Server........................................................................................... 43
Creating Server Groups ........................................................................................................................ 45
Registering Servers .............................................................................................................................. 46
Using Central Management Servers ..................................................................................................... 47

Configuring Server Agent for Multi-Server Environments .............................................. 51


MSDB Roles .......................................................................................................................................... 52
Configuring Master and Target Server .................................................................................................. 53
Creating Multi-Server Jobs................................................................................................................... 61

Summary ........................................................................................................................ 75
■Chapter 4: Metadata-Driven Automation ............................................................. 77
Creating Intelligent Routines .......................................................................................... 77
Configuring a Consistent Port Number ................................................................................................. 77
Profiling an Instance Workload ............................................................................................................. 81
Query Store Metadata........................................................................................................................... 83
Dynamic Index Rebuilds ....................................................................................................................... 92
Enforcing Policies ................................................................................................................................. 96

Analyzing Performance Counters ................................................................................. 100


Summary ...................................................................................................................... 104
■Chapter 5: Automation Techniques with SSIS ................................................... 105
SSIS Concepts .............................................................................................................. 105
SSIS Components ............................................................................................................................... 105
Getting Started ................................................................................................................................... 106
Creating a Simple Package................................................................................................................. 108

viii
CONTENTS ■

Adding Extra Functionality ........................................................................................... 118


Creating Event Handlers ..................................................................................................................... 119
Run Against Each Server in the Enterprise ......................................................................................... 136

Automation Recipes ..................................................................................................... 140


Verifying Backups ............................................................................................................................... 140
Respond to Operating System Events ................................................................................................ 148

Summary ...................................................................................................................... 156


■Chapter 6: Building an Inventory Database ....................................................... 157
Inventory Database Platform Design ............................................................................ 157
Inventory Database Logical Design .............................................................................. 160
Normalization ..................................................................................................................................... 161
Testing Normalization ......................................................................................................................... 166

Inventory Database Physical Design ............................................................................ 169


Creating the Database .................................................................................................. 172
Summary ...................................................................................................................... 175
■Chapter 7: Automating Instance Builds ............................................................. 177
Building the Instance.................................................................................................... 177
Performing a Simple Installation ........................................................................................................ 180
Using a Configuration File................................................................................................................... 183
Parameterizing the Script ................................................................................................................... 192

Configuring the Instance .............................................................................................. 193


Configure Database Scoped Configurations ....................................................................................... 193
Configure the Port Number ................................................................................................................. 197

Updating the Inventory Database ................................................................................. 198


Orchestrating the Build ................................................................................................ 202
Summary ...................................................................................................................... 204

ix
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
■ CONTENTS

■Chapter 8: Driving Automation Through Monitoring ......................................... 205


Working with Data Collection and the Management Data Warehouse ......................... 205
Understanding Data Collection ........................................................................................................... 205
Simple Implementation of Management Data Warehouse ................................................................. 207
Custom Implementation of Management Data Warehouse ................................................................ 218

Advanced Monitoring Techniques................................................................................. 224


Architecting the Custom Collection Solution ...................................................................................... 224
Building the Solution .......................................................................................................................... 225

Using Monitoring to Drive Automation.......................................................................... 250


Summary ...................................................................................................................... 252
■Chapter 9: Automating Routine Maintenance and Break/Fix Scenarios............ 253
Automating Routine Maintenance ................................................................................ 253
Automating Patching Activity .............................................................................................................. 253
Automating Environment Refreshes ................................................................................................... 258

Automating Break/Fix Scenarios .................................................................................. 269


Designing a Response to 9002 Errors ................................................................................................ 270
Automating a Response to 9002 Errors .............................................................................................. 271

Summary ...................................................................................................................... 279

■Index .................................................................................................................. 281

x
About the Author

Peter A. Carter is an SQL Server expert with more than a decade of


experience in developing, administering, and architecting SQL Server
platforms, data-tier applications, and ETL solutions. Peter has a passion
for SQL Server and hopes that his enthusiasm for this technology helps or
inspires others.

xi
About the Technical Reviewer

Philip Browne has been in the IT industry for nearly 20 years, starting with
client and infrastructure solutions for business, with his main areas of
expertise being application development (VB, VB.NET), web technologies
and Microsoft SQL products, and developing and releasing various
software applications, front ends, and custom tools. Philip also has a real
passion for hardware and systems security. He currently holds various
Microsoft certifications and works as an applications developer with
Microsoft’s latest technologies, SQL products, T-SQL, SSIS, and SSRS for
Millbrook Industries HQ in Totton, Southampton, England, with a great
team. Philip can be reached at philip.browne@ntlworld.com.

xiii
Introduction

As the ratio of DBAs to supported instances and supported databases continues to drop, DBAs must look
to automation, to allow them to continue to improve or, in some cases, even offer the same level of service
to the business as they have historically. This book attempts to give DBAs the tools they need to implement
strategic automation solutions, using the Microsoft standard suite of tools, specifically, PowerShell, T-SQL,
and SQL Server Agent.
Some large enterprises will be lucky enough to have enterprise class monitoring and orchestration
toolsets at their disposal. Even if this is the case, DBAs should find the scripts and the ideas for automated
scenarios contained within this book useful, as they can be plugged into enterprise class toolsets, despite
this book focusing on DBA written orchestrations.
The majority of examples in this book, use the topology laid out in Figure 1.

Figure 1. Topology
xv
■ INTRODUCTION

ESASSMGMT1 is a management server, while ESPROD1, ESPROD2, and ESPROD3 represent servers used
by the business. Each server has a default instance of SQL Server 2016 installed, both the instances
host a copy of the AdventureWorks2016 database. The AdventureWorks2016 database can be downloaded
from www.microsoft.com/en-us/download/details.aspx?id=49502.
If you wish to follow the examples and demonstrations in this book, you may choose to configure a
similar topology, or you can simply change the server\instance and database names in the script.
As you move through the book, you will create further instances, in order to learn the skills required
for automating instance builds. In Chapter 9, you will also learn how to automate patching routines. For
this demonstration, I use two SQL Server 2014 instances called ESPRODSQL14_001\SQL14INSTANCE1 and
ESPRODSQL14_001\SQL14INSTANCE2. SQL Server 2014 instances were used for this demonstration, due to
no SQL Server 2016 patches being available at the time of writing. When following the demonstrations,
however, you may choose to use either SQL Server 2014 or existing SQL Server 2016 instances that you have
used in other chapters of the book (subject to availability of patches).

xvi
CHAPTER 1

T-SQL Techniques for DBAs

As a DBA, you will almost certainly understand the basics of the T-SQL language and use it for querying
metadata views, such as sys.databases or sys.tables. Often, DBAs do not have advanced T-SQL
skills, however, as they do not need them in day-to-day operations. In order to implement sophisticated
automation and, in turn, reduce operational costs and overheads, DBAs should gain an understanding of
some more advanced scripting techniques. Therefore, this chapter will focus on exploring some of the T-SQL
techniques that we will use in this book. I will make the assumption that if you are reading this book, you
are familiar with rudimentary T-SQL, such as the SELECT statement, including FROM, JOIN, WHERE, GROUP BY,
HAVING, and ORDER BY clauses. If you do need a refresher, however, full details of the SELECT statement can be
found at https://msdn.microsoft.com/en-us/library/ms189499.aspx#.
We will start by looking at the APPLY operator to call a function against rows within a result set. We will
then look at how XML (eXtensible Markup Language) and how the native XML data type can be harnessed
by SQL Server DBAs. It is critical for DBAs to have a handle on the use of XML, due to the volume of metrics
and information that are exposed via this data type. We will then explore how to efficiently iterate through
multiple objects.

Using the APPLY Operator


The T-SQL APPLY operator allows you to call a table valued function against every row in a result set
returned by a query. There are two variations of the APPLY operator: CROSS APPLY and OUTER APPLY. When
CROSS APPLY is used, the query will only return rows in which a result set has been produced by the table
valued function. When OUTER APPLY is used, no filter will be applied to the result set, and where no result is
returned by the table valued function, NULL will be returned, in each column of the table valued function.
The APPLY operator can be very useful to DBAs when they are retrieving metadata from dynamic
management views (DMV) and functions (DMF). For example, the query in Listing 1-1 will return a list of all
sessions, detailing the session ID, the login time, the login name, and whether the process is a user or system
process. It will then use OUTER APPLY to run the sys.dm_exec_sql_text dynamic management function
against each row. This function returns a column called text, which is the SQL statement associated with the
SQL handle in the sql_handle column in the sys.dm_exec_requests dynamic management view.

■ Note The text column that is referenced in the SELECT list is the column returned by the
sys.dm_exec_sql_text DMF.

Electronic supplementary material The online version of this chapter (doi:10.1007/978-1-4842-1943-0_1)


contains supplementary material, which is available to authorized users.

© Peter A. Carter 2016 1


P. A. Carter, Expert Scripting and Automation for SQL Server DBAs, DOI 10.1007/978-1-4842-1943-0_1
CHAPTER 1 ■ T-SQL TECHNIQUES FOR DBAS

Listing 1-1. Using OUTER APPLY


SELECT s.session_id
,s.login_time
,s.login_name
,s.is_user_process
,[text]
FROM sys.dm_exec_sessions s
INNER JOIN sys.dm_exec_requests r
ON r.session_id = s.session_id
OUTER APPLY sys.dm_exec_sql_text(sql_handle) ;

You will notice that this query returns many rows in this result set with NULL values for the text column.
This is because they are system processes, running background tasks for SQL Server, such as the Lazy Writer
and the Ghost Cleanup Task.

■ Tip We can be sure that they are system processes because of the is_user_process flag. We will not
rely on the session ID being less than 50. The assertion that all system processes have a session ID of less
than 50 is widely believed, but also a fallacy, because there can potentially be more than 50 system sessions
running in parallel.

If we use the CROSS APPLY operator for the same query, as shown in Listing 1-2, the only rows that will
be returned will be rows where the result of applying the tabled valued function is not NULL.

Listing 1-2. Using APPLY


SELECT s.session_id
,s.login_time
,s.login_name
,[text]
,s.is_user_process
FROM sys.dm_exec_sessions s
INNER JOIN sys.dm_exec_requests r
ON r.session_id = s.session_id
CROSS APPLY sys.dm_exec_sql_text(sql_handle) ;

Understanding XML
XML is a markup language, similar to HTML, that was designed for the purpose of storing and transporting
data. Like HTML, XML consists of tags. Unlike HTML, however, these tags are not predefined. Instead, they
are defined by the document author. An XML document has a tree structure, beginning with a root node and
containing child nodes (also known as child elements). Each element can contain data but also attributes.
Each attribute can contain data that describes the element. For example, imagine that you require details
of sales orders to be stored in XML format. It would be sensible to assume that each sales order would be
stored in a separate element within the document. But what about sales order properties, such as order date,
customer ID, product IDs, quantities, and prices? These pieces of information could either be stored as child
elements of the sales order element, or they could be stored as attributes of the sales order element. There
are no set rules for when you should use child elements or attributes to describe properties of an element.
This choice is at the discretion of the document author. The XML document in Listing 1-3 provides a sample
XML document, which holds the details of sales orders for a fictional organization.

2
CHAPTER 1 ■ T-SQL TECHNIQUES FOR DBAS

Listing 1-3. Sales Orders Stored in an XML Document


<SalesOrders>
<SalesOrder CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659">
<LineItem UnitPrice="2024.9940" OrderQty="1" />
<LineItem UnitPrice="2024.9940" OrderQty="3" />
<LineItem UnitPrice="2024.9940" OrderQty="1" />
<LineItem UnitPrice="2039.9940" OrderQty="1" />
<LineItem UnitPrice="2039.9940" OrderQty="1" />
<LineItem UnitPrice="2039.9940" OrderQty="2" />
<LineItem UnitPrice="2039.9940" OrderQty="1" />
<LineItem UnitPrice="28.8404" OrderQty="3" />
<LineItem UnitPrice="28.8404" OrderQty="1" />
<LineItem UnitPrice="5.7000" OrderQty="6" />
<LineItem UnitPrice="5.1865" OrderQty="2" />
<LineItem UnitPrice="20.1865" OrderQty="4" />
</SalesOrder>
<SalesOrder CustomerID="29825" OrderDate="2011-08-31T00:00:00" SalesOrderID="44305">
<LineItem UnitPrice="2024.9940" OrderQty="2" />
<LineItem UnitPrice="2039.9940" OrderQty="2" />
<LineItem UnitPrice="2039.9940" OrderQty="2" />
<LineItem UnitPrice="2039.9940" OrderQty="2" />
<LineItem UnitPrice="714.7043" OrderQty="2" />
<LineItem UnitPrice="818.7000" OrderQty="1" />
<LineItem UnitPrice="28.8404" OrderQty="2" />
<LineItem UnitPrice="28.8404" OrderQty="1" />
<LineItem UnitPrice="28.8404" OrderQty="2" />
<LineItem UnitPrice="5.5100" OrderQty="12" />
<LineItem UnitPrice="5.7000" OrderQty="3" />
<LineItem UnitPrice="5.1865" OrderQty="3" />
<LineItem UnitPrice="20.1865" OrderQty="2" />
<LineItem UnitPrice="20.1865" OrderQty="2" />
<LineItem UnitPrice="20.1865" OrderQty="1" />
</SalesOrder>
<SalesOrder CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061">
<LineItem UnitPrice="2024.9940" OrderQty="3" />
<LineItem UnitPrice="2024.9940" OrderQty="2" />
<LineItem UnitPrice="2024.9940" OrderQty="5" />
<LineItem UnitPrice="2024.9940" OrderQty="8" />
<LineItem UnitPrice="2039.9940" OrderQty="6" />
<LineItem UnitPrice="2039.9940" OrderQty="2" />
<LineItem UnitPrice="2039.9940" OrderQty="5" />
<LineItem UnitPrice="2039.9940" OrderQty="5" />
<LineItem UnitPrice="28.8404" OrderQty="2" />
<LineItem UnitPrice="5.7000" OrderQty="5" />
<LineItem UnitPrice="5.1865" OrderQty="1" />
</SalesOrder>
</SalesOrders>

3
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
CHAPTER 1 ■ T-SQL TECHNIQUES FOR DBAS

There are several things to note when looking at this XML document. First, elements begin with the
element name, encapsulated within angle brackets. They end with the element name, preceded by a
backslash and enclosed in angle brackets. Any elements that fall between these two tags are child elements
of the tag.
Attributes are enclosed in double quotation marks and reside within the beginning tag of an element.
For example, OrderID is an attribute of the <SalesOrder> element.
It is acceptable to have repeating elements. You can see that <SalesOrder> is a repeating element, as
two separate sales orders are stored in this XML document. The <SalesOrders> element is the document’s
root element and is the only element that is not allowed to be complex. This means that it cannot have
attributes and cannot be repeating. Attributes can never repeat within an element. Therefore, if you require a
node to repeat, you should use a nested element as opposed to an attribute.
The format of an XML document can be defined by an XSD schema. An XSD schema will define the
document’s structure, including data types, if complex types (complex elements) are allowed, and how many
times an element must occur (or is limited to occurring) within a document. It also defines the sequence of
elements. A full description of XSD schemas can be found at en.wikipedia.org/wiki/XML_Schema_(W3C).

■ Tip An XML document requires a root element in order to be “well-formed.” An XML document without a root
element is known as an XML fragment. This is important, because it is not possible to bind an XML fragment to an
XSD schema. This means that the structure of the document, including data types, cannot be enforced.

Converting Results Sets to XML


T-SQL allows you to convert relational results sets into XML, by using the FOR XML clause in your SELECT
statement. There are four modes that can be used with the FOR XML clause: FOR XML RAW, FOR XML AUTO, FOR
XML PATH, and FOR XML EXPLICIT. The following sections will demonstrate how the FOR XML clause works in
RAW mode, AUTO mode, and PATH mode. EXPLICIT mode is beyond the scope of this book, as its functionality
is very similar to PATH mode but is far more complex and does not often prove useful for DBAs.

■ Note The value of a DBA understanding FOR XML will become evident in Chapter 8.

Using FOR XML RAW


The simplest and easiest to understand of the FOR XML modes is FOR XML RAW. This mode will transform each
row in a relational result set into an element within a flat XML document. Consider the query in Listing 1-4,
which extracts details of a sales order from the AdventureWorks2016 database.

Listing 1-4. AdventureWorks Sales Order Query


SELECT
SalesOrder.CustomerID
,SalesOrder.OrderDate
,SalesOrder.SalesOrderID
,LineItem.UnitPrice
,LineItem.OrderQty
,p.Name

4
CHAPTER 1 ■ T-SQL TECHNIQUES FOR DBAS

FROM Sales.SalesOrderHeader SalesOrder


INNER JOIN Sales.SalesOrderDetail LineItem
ON SalesOrder.SalesOrderID = LineItem.SalesOrderID
INNER JOIN Production.Product P
ON LineItem.ProductID = p.ProductID
WHERE SalesOrder.CustomerID = 29825
AND SalesOrder.OrderDate < '2012-01-01' ;

This query extracts the details of orders placed by customer 29825, before January 1, 2012. A partial
output of the query can be found in Figure 1-1.

Figure 1-1. AdventureWorks sales order output

If we were to add a FOR XML clause using RAW mode, the results would be returned in the form of an XML
fragment. The amended query in Listing 1-5 will return the XML document instead of a relational result set.

Listing 1-5. AdventurWorks Sales Orders Using FOR XML RAW


SELECT
SalesOrder.CustomerID
,SalesOrder.OrderDate
5
CHAPTER 1 ■ T-SQL TECHNIQUES FOR DBAS

,SalesOrder.SalesOrderID
,LineItem.UnitPrice
,LineItem.OrderQty
,p.Name
FROM Sales.SalesOrderHeader SalesOrder
INNER JOIN Sales.SalesOrderDetail LineItem
ON SalesOrder.SalesOrderID = LineItem.SalesOrderID
INNER JOIN Production.Product P
ON LineItem.ProductID = p.ProductID
WHERE SalesOrder.CustomerID = 29825
AND SalesOrder.OrderDate < '2012-01-01'
FOR XML RAW, ROOT('SalesOrders') ;

Listing 1-6 illustrates the XML document that is returned. This is only a partial results set, as some
results have been omitted to save space. Breaks in results are marked with an ellipse.

Listing 1-6. AdventurWorks Sales Orders Using FOR XML RAW—Partial Results
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2024.9940" OrderQty="1" Name="Mountain-100 Black, 42" />
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2024.9940" OrderQty="3" Name="Mountain-100 Black, 44" />
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2024.9940" OrderQty="1" Name="Mountain-100 Black, 48" />
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2039.9940" OrderQty="1" Name="Mountain-100 Silver, 38" />
...
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="2039.9940" OrderQty="5" Name="Mountain-100 Silver, 48" />
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="28.8404" OrderQty="2" Name="Long-Sleeve Logo Jersey, L" />
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="5.7000" OrderQty="5" Name="Mountain Bike Socks, M" />
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="5.1865" OrderQty="1" Name="AWC Logo Cap" />

The first thing that we should note about this document is that it is an XML fragment, as opposed to a
well-formed XML document, because there is no root node. The <row> element cannot be the root node,
because it repeats. This means that we cannot validate the XML against a schema. Therefore, when using the
FOR XML clause, you should consider using the ROOT keyword. This will force a root element, with a name of
your choosing, to be created within the document. This is demonstrated in Listing 1-7.

Listing 1-7. Adding a Root Node


SELECT
SalesOrder.CustomerID
,SalesOrder.OrderDate
,SalesOrder.SalesOrderID
,LineItem.UnitPrice
,LineItem.OrderQty
,p.Name
FROM Sales.SalesOrderHeader SalesOrder

6
CHAPTER 1 ■ T-SQL TECHNIQUES FOR DBAS

INNER JOIN Sales.SalesOrderDetail LineItem


ON SalesOrder.SalesOrderID = LineItem.SalesOrderID
INNER JOIN Production.Product P
ON LineItem.ProductID = p.ProductID
WHERE SalesOrder.CustomerID = 29825
AND SalesOrder.OrderDate < '2012-01-01'
FOR XML RAW, ROOT('SalesOrders') ;

Partial output of the resulting well-formed XML document can be found in Listing 1-8.

Listing 1-8. Partial Output of XML Document with Root Node


<SalesOrders>
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2024.9940" OrderQty="1" Name="Mountain-100 Black, 42" />
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2024.9940" OrderQty="3" Name="Mountain-100 Black, 44" />
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2024.9940" OrderQty="1" Name="Mountain-100 Black, 48" />
<row CustomerID="29825" OrderDate="2011-05-31T00:00:00" SalesOrderID="43659"
UnitPrice="2039.9940" OrderQty="1" Name="Mountain-100 Silver, 38" />
...
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="2039.9940" OrderQty="5" Name="Mountain-100 Silver, 48" />
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="28.8404" OrderQty="2" Name="Long-Sleeve Logo Jersey, L" />
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="5.7000" OrderQty="5" Name="Mountain Bike Socks, M" />
<row CustomerID="29825" OrderDate="2011-12-01T00:00:00" SalesOrderID="45061"
UnitPrice="5.1865" OrderQty="1" Name="AWC Logo Cap" />
</SalesOrders>

The other important thing to notice about the document is that it is completely flat. There is no nesting.
This means that the document’s granularity is at the level of line item, which does not make a lot of sense.
It is also worth noting that all data is contained in attributes, as opposed to elements. We can alter this
behavior by using the ELEMENTS keyword in the FOR XML clause. The ELEMENTS keyword will cause all data to
be contained within child elements, as opposed to attributes. This is demonstrated in the modified query
that can be found in Listing 1-9.

Listing 1-9. Using the ELEMENTS Keyword


SELECT
SalesOrder.CustomerID
,SalesOrder.OrderDate
,SalesOrder.SalesOrderID
,LineItem.UnitPrice
,LineItem.OrderQty
,p.Name
FROM Sales.SalesOrderHeader SalesOrder
INNER JOIN Sales.SalesOrderDetail LineItem
ON SalesOrder.SalesOrderID = LineItem.SalesOrderID
INNER JOIN Production.Product P
ON LineItem.ProductID = p.ProductID
7
CHAPTER 1 ■ T-SQL TECHNIQUES FOR DBAS

WHERE SalesOrder.CustomerID = 29825


AND SalesOrder.OrderDate < '2012-01-01'
FOR XML RAW, ELEMENTS, ROOT('SalesOrders') ;

The well-formed XML document that is returned can be partially seen in Listing 1-10.

Listing 1-10. Using the ELEMENTS Keyword—Partial Results


<SalesOrders>
<row>
<CustomerID>29825</CustomerID>
<OrderDate>2011-05-31T00:00:00</OrderDate>
<SalesOrderID>43659</SalesOrderID>
<UnitPrice>2024.9940</UnitPrice>
<OrderQty>1</OrderQty>
<Name>Mountain-100 Black, 42</Name>
</row>
<row>
<CustomerID>29825</CustomerID>
<OrderDate>2011-05-31T00:00:00</OrderDate>
<SalesOrderID>43659</SalesOrderID>
<UnitPrice>2024.9940</UnitPrice>
<OrderQty>3</OrderQty>
<Name>Mountain-100 Black, 44</Name>
</row>
<row>
<CustomerID>29825</CustomerID>
<OrderDate>2011-05-31T00:00:00</OrderDate>
<SalesOrderID>43659</SalesOrderID>
<UnitPrice>2024.9940</UnitPrice>
<OrderQty>1</OrderQty>
<Name>Mountain-100 Black, 48</Name>
</row>
<row>
<CustomerID>29825</CustomerID>
<OrderDate>2011-05-31T00:00:00</OrderDate>
<SalesOrderID>43659</SalesOrderID>
<UnitPrice>2039.9940</UnitPrice>
<OrderQty>1</OrderQty>
<Name>Mountain-100 Silver, 38</Name>
</row>
...
<row>
<CustomerID>29825</CustomerID>
<OrderDate>2011-12-01T00:00:00</OrderDate>
<SalesOrderID>45061</SalesOrderID>
<UnitPrice>2039.9940</UnitPrice>
<OrderQty>5</OrderQty>
<Name>Mountain-100 Silver, 48</Name>
</row>

8
Random documents with unrelated
content Scribd suggests to you:
The caretaker closed his eyes. "You're not supposed to know about
such things." The eyes remained closed. "Anyway, the switches are
below. Atom bomb shelter built hundreds of years ago and never
used." The eyes came open. "Know anything about atom bombs?"
"Not a thing," said Danny and walked away. He knew about atom
bombs but he didn't have one. And short of that there was no way to
interrupt the power.
Twenty-five minutes left, and it seemed impossible to get to the meta
piano circuits.
The robot piano master was his last hope. Disable it and the critical
part of the program would have to be cancelled.
Danny started the search. The music robots, motionless and silent,
were seated near the orchestra entrance. The piano robot was not
with them.
Acting on a hunch, Danny located the dressing rooms. One by one he
went through them. A robot had no need for privacy, but in the third
room he found the piano robot. It was listening to music. Vaguely he
was disturbed. Generally robots merely reproduced music; they didn't
listen to it. Evidently the piano robot was different in ways he hadn't
suspected. He'd have to find out about that, later.
He located a short length of metal bar and softly opened the door.
The piano robot was still intently listening. A blow from behind
knocked it sprawling. Instantly Danny followed with another blow to
the side of the head. The robot jerked spasmodically.
Methodically he pounded the hands and arms into a pulpy mass. It
wasn't flesh and it didn't look like it; through the synthetic skin
covering wires and metal joints splayed as he struck savagely.
"Piano master." Danny straightened up. The human announcer was
outside the door.
Danny looked around. There was no other exit save the way he had
come in. He turned the music louder. The meta piano was not safe
unless he could get out undetected. They would want to know the
reasons for his attack on the piano robot and they had means to find
out.
"Piano Master." The voice was louder, more insistent.
"Yes?" Danny muffled his voice, spoke through the music.
"The program will begin in ten minutes."
"I know. I'll be there."
"The music committee is waiting to accompany you. When will you be
ready?"
He was caught by the logic of the occasion. Normally no one
bothered with the piano robot. But this was a big event and old
traditions had been resurrected for it. "I'm listening to the music,"
said Danny. "I'll be ready."

He stripped clothing off the inert robot. Forked black coat and a
ridiculous string around his throat: the uniform of the music robot.
The existence of such a uniform would help him. Hastily he changed,
tossing his own clothing in a corner. He was half a head taller than
the piano master, and broader in the shoulders. The sleeves and
trousers were too short. He stretched them to fit. Another inch more
would have been more than the fabric would lengthen.
Danny's hair was light brown; the robot piano master's an iron grey.
Under stage lighting it might not be noticed. He rumpled his hair to
conform to standards.
Did anyone look at a robot's face? Danny hoped not; there was
nothing he could do about his. He dragged the robot behind a chair,
and, assuming a masklike, tranquil expression, walked out of the
dressing room as if in a trance.
No one noticed anything. Nodding, the announcer led him to the
stage. The committee followed and sat at one side of the stage. So
far Danny had passed.
He had read the program and knew what was to occur. An
introductory piano concerto and then the event of the evening. Or
perhaps the decade. It rated a human announcer and was probably
broadcast to three worlds.
The important thing was the sequence of notes in Flee As A Bird. If it
were played exactly as he had keyed it in, the meta piano would go
into operation. Once they heard it the audience would never mistake
it for any other instrument.
But the sequence was long. If he could alter it by as little as two
notes the sonic switch would not operate. It was worth trying.
Outside the enclosure the announcer was making a speech. The
audience applauded and then it was his cue.
He smiled ironically. He had never hoped for an audience, and now
he had one. It was a debut he didn't care for.
He struck the opening bars of the concerto. The keys rippled under
his fingers. He played with the uninspired competence that was
expected of a music robot.
It was time for the trumpets to come in, but they didn't. And the
violins were long overdue with a repeat of his opening phrase. The
orchestra was supposed to play with the piano and it wasn't doing so.
Danny looked at the audience; something was wrong: even they
knew it. What was it? Danny glanced over his shoulder at the
orchestra.
The robots stood there uneasily, dummy instruments poised. Not a
sound came from the mechanism concealed in their bodies. For some
reason they could not follow his lead.
He let a note drop from his fingers and stared around. It wasn't going
the way he had planned. The announcer stepped into the gap.
"Due to an unexpected technical failure, we are unable to present the
concerto as scheduled. There will be a brief delay and then the main
event of the evening will follow."
Ad libbing, of course. The announcer didn't know what had
happened. But he had observed that Danny was playing and the
orchestra was not. It would seem logical to him that the fault lay in
the orchestra and not with the piano.
Actually, Danny now realized, it was the reverse. The piano robot was
the leader of the orchestra. It was different; it coordinated the
activities of the other robots, gave them the rhythm, a purpose.
Better musician or not, Danny couldn't fill that role. He was a man,
not a machine, and his mind did not function on an electronic level.
Danny glanced at the wings of the stage. No matter what he did now
he was lost. The robot piano master stood out of sight of the
audience and the announcer, broken arms drooping. Beside him were
half a dozen members of the psych squad.
The audience was restless, and puzzled. As full as the auditorium
was, there was room for a few more men who slipped in quietly and
took their stations by the exits. They were probably armed.

Danny faced the piano. They had come to hear an old melody, and
he would give it to them. Flee As A Bird To The Mountain. It was a
New Orleans funeral march, and that was fitting. It was the end of
him as a musician.
He let the first notes roll off his fingers, slow. The music had been
buried three hundred years and it was still good. It hadn't been worn
out with too much listening.
He got through the first chorus and the audience was listening. They
didn't know it, but it was human music they were responding to.
The sonic switch closed and the meta piano took over. Danny had
built it and it was to the piano as the piano was to a harpsichord. It
was a solitary instrument but an orchestra couldn't compete with it.
The sounding board of the original piano was not big enough. It was
designed to use the whole building and the air within it as the
vibrating medium. He had never used the full force of it before. But
he did now. Now was the time; he had nothing to lose.
He finished the New Orleans march on the meta piano and then let
them hear what music meant to him. His own compositions, carried
around in his memory because it was dangerous to let anyone know
he could write music. It was his audience and he was going to show
them what previously he had concealed. The technicians wouldn't
have enough presence of mind to cut him off the radio hookup.
He played them harmonies no one ever thought of; not only what
they heard, but also what they couldn't hear. Overtones piled high on
overtones until the last in the series were out of reach of the human
ear. Maybe the ears of dogs or bats too, but that didn't matter. It
didn't matter either that humans couldn't hear it. It was there and it
affected them.
It touched the auditory nerve endings and those nerves that had
nothing to do with the perception of sound. It moved with the hush
of a comet or shook like an exploding nucleus disrupts an atom. From
the big to the little and back again he took them on a musical tour of
the universe. No other charge than the price of admission.
It was his first concert and probably his last. When it was over he
leaned against the meta piano; it became silent and changed back
into the ordinary instrument.
The audience did not move and made no sound. He had expected
some reaction, but not this. He had hoped they would like it.
He bowed his head in defeat. When he looked up the audience still
had not moved. But the piano master stood at the entrance to the
enclosure. "These can be replaced," the robot whispered, holding out
his broken hands.
Then the piano master spoke loud enough for everyone to hear. "I
don't know anything about music. Will you teach me?"
That was the signal the audience was waiting for; the applause came
in waves that would not stop. It engulfed Danny and brought him
trembling to his feet. The thunder of sound increased in intensity
until it seemed as if the very walls would crash with the vibration.
And mingled with it he heard a swelling chorus of human voices
shouting a word long buried but now resurrected; Bravo! Bravo—
Bravo!
A smile crossed Danny's tense features and suddenly then he felt
relaxed; he glanced to the side of the stage, saw the piano robot
nodding approval, and beside the robot, the psych squad. The faces
had lost their sternness; there was an awe instead, and, Danny saw,
smiles....
Danny turned back to the audience and its continuing ovation.
He bowed humbly....
*** END OF THE PROJECT GUTENBERG EBOOK THE MUSIC
MASTER ***

Updated editions will replace the previous one—the old editions will
be renamed.

Creating the works from print editions not protected by U.S.


copyright law means that no one owns a United States copyright in
these works, so the Foundation (and you!) can copy and distribute it
in the United States without permission and without paying
copyright royalties. Special rules, set forth in the General Terms of
Use part of this license, apply to copying and distributing Project
Gutenberg™ electronic works to protect the PROJECT GUTENBERG™
concept and trademark. Project Gutenberg is a registered trademark,
and may not be used if you charge for an eBook, except by following
the terms of the trademark license, including paying royalties for use
of the Project Gutenberg trademark. If you do not charge anything
for copies of this eBook, complying with the trademark license is
very easy. You may use this eBook for nearly any purpose such as
creation of derivative works, reports, performances and research.
Project Gutenberg eBooks may be modified and printed and given
away—you may do practically ANYTHING in the United States with
eBooks not protected by U.S. copyright law. Redistribution is subject
to the trademark license, especially commercial redistribution.

START: FULL LICENSE


THE FULL PROJECT GUTENBERG LICENSE
PLEASE READ THIS BEFORE YOU DISTRIBUTE OR USE THIS WORK

To protect the Project Gutenberg™ mission of promoting the free


distribution of electronic works, by using or distributing this work (or
any other work associated in any way with the phrase “Project
Gutenberg”), you agree to comply with all the terms of the Full
Project Gutenberg™ License available with this file or online at
www.gutenberg.org/license.

Section 1. General Terms of Use and


Redistributing Project Gutenberg™
electronic works
1.A. By reading or using any part of this Project Gutenberg™
electronic work, you indicate that you have read, understand, agree
to and accept all the terms of this license and intellectual property
(trademark/copyright) agreement. If you do not agree to abide by all
the terms of this agreement, you must cease using and return or
destroy all copies of Project Gutenberg™ electronic works in your
possession. If you paid a fee for obtaining a copy of or access to a
Project Gutenberg™ electronic work and you do not agree to be
bound by the terms of this agreement, you may obtain a refund
from the person or entity to whom you paid the fee as set forth in
paragraph 1.E.8.

1.B. “Project Gutenberg” is a registered trademark. It may only be


used on or associated in any way with an electronic work by people
who agree to be bound by the terms of this agreement. There are a
few things that you can do with most Project Gutenberg™ electronic
works even without complying with the full terms of this agreement.
See paragraph 1.C below. There are a lot of things you can do with
Project Gutenberg™ electronic works if you follow the terms of this
agreement and help preserve free future access to Project
Gutenberg™ electronic works. See paragraph 1.E below.
1.C. The Project Gutenberg Literary Archive Foundation (“the
Foundation” or PGLAF), owns a compilation copyright in the
collection of Project Gutenberg™ electronic works. Nearly all the
individual works in the collection are in the public domain in the
United States. If an individual work is unprotected by copyright law
in the United States and you are located in the United States, we do
not claim a right to prevent you from copying, distributing,
performing, displaying or creating derivative works based on the
work as long as all references to Project Gutenberg are removed. Of
course, we hope that you will support the Project Gutenberg™
mission of promoting free access to electronic works by freely
sharing Project Gutenberg™ works in compliance with the terms of
this agreement for keeping the Project Gutenberg™ name associated
with the work. You can easily comply with the terms of this
agreement by keeping this work in the same format with its attached
full Project Gutenberg™ License when you share it without charge
with others.

1.D. The copyright laws of the place where you are located also
govern what you can do with this work. Copyright laws in most
countries are in a constant state of change. If you are outside the
United States, check the laws of your country in addition to the
terms of this agreement before downloading, copying, displaying,
performing, distributing or creating derivative works based on this
work or any other Project Gutenberg™ work. The Foundation makes
no representations concerning the copyright status of any work in
any country other than the United States.

1.E. Unless you have removed all references to Project Gutenberg:

1.E.1. The following sentence, with active links to, or other


immediate access to, the full Project Gutenberg™ License must
appear prominently whenever any copy of a Project Gutenberg™
work (any work on which the phrase “Project Gutenberg” appears,
or with which the phrase “Project Gutenberg” is associated) is
accessed, displayed, performed, viewed, copied or distributed:
This eBook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this eBook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.

1.E.2. If an individual Project Gutenberg™ electronic work is derived


from texts not protected by U.S. copyright law (does not contain a
notice indicating that it is posted with permission of the copyright
holder), the work can be copied and distributed to anyone in the
United States without paying any fees or charges. If you are
redistributing or providing access to a work with the phrase “Project
Gutenberg” associated with or appearing on the work, you must
comply either with the requirements of paragraphs 1.E.1 through
1.E.7 or obtain permission for the use of the work and the Project
Gutenberg™ trademark as set forth in paragraphs 1.E.8 or 1.E.9.

1.E.3. If an individual Project Gutenberg™ electronic work is posted


with the permission of the copyright holder, your use and distribution
must comply with both paragraphs 1.E.1 through 1.E.7 and any
additional terms imposed by the copyright holder. Additional terms
will be linked to the Project Gutenberg™ License for all works posted
with the permission of the copyright holder found at the beginning
of this work.

1.E.4. Do not unlink or detach or remove the full Project


Gutenberg™ License terms from this work, or any files containing a
part of this work or any other work associated with Project
Gutenberg™.

1.E.5. Do not copy, display, perform, distribute or redistribute this


electronic work, or any part of this electronic work, without
prominently displaying the sentence set forth in paragraph 1.E.1
with active links or immediate access to the full terms of the Project
Gutenberg™ License.

1.E.6. You may convert to and distribute this work in any binary,
compressed, marked up, nonproprietary or proprietary form,
including any word processing or hypertext form. However, if you
provide access to or distribute copies of a Project Gutenberg™ work
in a format other than “Plain Vanilla ASCII” or other format used in
the official version posted on the official Project Gutenberg™ website
(www.gutenberg.org), you must, at no additional cost, fee or
expense to the user, provide a copy, a means of exporting a copy, or
a means of obtaining a copy upon request, of the work in its original
“Plain Vanilla ASCII” or other form. Any alternate format must
include the full Project Gutenberg™ License as specified in
paragraph 1.E.1.

1.E.7. Do not charge a fee for access to, viewing, displaying,


performing, copying or distributing any Project Gutenberg™ works
unless you comply with paragraph 1.E.8 or 1.E.9.

1.E.8. You may charge a reasonable fee for copies of or providing


access to or distributing Project Gutenberg™ electronic works
provided that:

• You pay a royalty fee of 20% of the gross profits you derive
from the use of Project Gutenberg™ works calculated using the
method you already use to calculate your applicable taxes. The
fee is owed to the owner of the Project Gutenberg™ trademark,
but he has agreed to donate royalties under this paragraph to
the Project Gutenberg Literary Archive Foundation. Royalty
payments must be paid within 60 days following each date on
which you prepare (or are legally required to prepare) your
periodic tax returns. Royalty payments should be clearly marked
as such and sent to the Project Gutenberg Literary Archive
Foundation at the address specified in Section 4, “Information
about donations to the Project Gutenberg Literary Archive
Foundation.”

• You provide a full refund of any money paid by a user who


notifies you in writing (or by e-mail) within 30 days of receipt
that s/he does not agree to the terms of the full Project
Gutenberg™ License. You must require such a user to return or
destroy all copies of the works possessed in a physical medium
and discontinue all use of and all access to other copies of
Project Gutenberg™ works.

• You provide, in accordance with paragraph 1.F.3, a full refund of


any money paid for a work or a replacement copy, if a defect in
the electronic work is discovered and reported to you within 90
days of receipt of the work.

• You comply with all other terms of this agreement for free
distribution of Project Gutenberg™ works.

1.E.9. If you wish to charge a fee or distribute a Project Gutenberg™


electronic work or group of works on different terms than are set
forth in this agreement, you must obtain permission in writing from
the Project Gutenberg Literary Archive Foundation, the manager of
the Project Gutenberg™ trademark. Contact the Foundation as set
forth in Section 3 below.

1.F.

1.F.1. Project Gutenberg volunteers and employees expend


considerable effort to identify, do copyright research on, transcribe
and proofread works not protected by U.S. copyright law in creating
the Project Gutenberg™ collection. Despite these efforts, Project
Gutenberg™ electronic works, and the medium on which they may
be stored, may contain “Defects,” such as, but not limited to,
incomplete, inaccurate or corrupt data, transcription errors, a
copyright or other intellectual property infringement, a defective or
damaged disk or other medium, a computer virus, or computer
codes that damage or cannot be read by your equipment.

1.F.2. LIMITED WARRANTY, DISCLAIMER OF DAMAGES - Except for


the “Right of Replacement or Refund” described in paragraph 1.F.3,
the Project Gutenberg Literary Archive Foundation, the owner of the
Project Gutenberg™ trademark, and any other party distributing a
Project Gutenberg™ electronic work under this agreement, disclaim
all liability to you for damages, costs and expenses, including legal
fees. YOU AGREE THAT YOU HAVE NO REMEDIES FOR
NEGLIGENCE, STRICT LIABILITY, BREACH OF WARRANTY OR
BREACH OF CONTRACT EXCEPT THOSE PROVIDED IN PARAGRAPH
1.F.3. YOU AGREE THAT THE FOUNDATION, THE TRADEMARK
OWNER, AND ANY DISTRIBUTOR UNDER THIS AGREEMENT WILL
NOT BE LIABLE TO YOU FOR ACTUAL, DIRECT, INDIRECT,
CONSEQUENTIAL, PUNITIVE OR INCIDENTAL DAMAGES EVEN IF
YOU GIVE NOTICE OF THE POSSIBILITY OF SUCH DAMAGE.

1.F.3. LIMITED RIGHT OF REPLACEMENT OR REFUND - If you


discover a defect in this electronic work within 90 days of receiving
it, you can receive a refund of the money (if any) you paid for it by
sending a written explanation to the person you received the work
from. If you received the work on a physical medium, you must
return the medium with your written explanation. The person or
entity that provided you with the defective work may elect to provide
a replacement copy in lieu of a refund. If you received the work
electronically, the person or entity providing it to you may choose to
give you a second opportunity to receive the work electronically in
lieu of a refund. If the second copy is also defective, you may
demand a refund in writing without further opportunities to fix the
problem.

1.F.4. Except for the limited right of replacement or refund set forth
in paragraph 1.F.3, this work is provided to you ‘AS-IS’, WITH NO
OTHER WARRANTIES OF ANY KIND, EXPRESS OR IMPLIED,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF
MERCHANTABILITY OR FITNESS FOR ANY PURPOSE.

1.F.5. Some states do not allow disclaimers of certain implied


warranties or the exclusion or limitation of certain types of damages.
If any disclaimer or limitation set forth in this agreement violates the
law of the state applicable to this agreement, the agreement shall be
interpreted to make the maximum disclaimer or limitation permitted
by the applicable state law. The invalidity or unenforceability of any
provision of this agreement shall not void the remaining provisions.

1.F.6. INDEMNITY - You agree to indemnify and hold the Foundation,


the trademark owner, any agent or employee of the Foundation,
anyone providing copies of Project Gutenberg™ electronic works in
accordance with this agreement, and any volunteers associated with
the production, promotion and distribution of Project Gutenberg™
electronic works, harmless from all liability, costs and expenses,
including legal fees, that arise directly or indirectly from any of the
following which you do or cause to occur: (a) distribution of this or
any Project Gutenberg™ work, (b) alteration, modification, or
additions or deletions to any Project Gutenberg™ work, and (c) any
Defect you cause.

Section 2. Information about the Mission


of Project Gutenberg™
Project Gutenberg™ is synonymous with the free distribution of
electronic works in formats readable by the widest variety of
computers including obsolete, old, middle-aged and new computers.
It exists because of the efforts of hundreds of volunteers and
donations from people in all walks of life.

Volunteers and financial support to provide volunteers with the


assistance they need are critical to reaching Project Gutenberg™’s
goals and ensuring that the Project Gutenberg™ collection will
remain freely available for generations to come. In 2001, the Project
Gutenberg Literary Archive Foundation was created to provide a
secure and permanent future for Project Gutenberg™ and future
generations. To learn more about the Project Gutenberg Literary
Archive Foundation and how your efforts and donations can help,
see Sections 3 and 4 and the Foundation information page at
www.gutenberg.org.

Section 3. Information about the Project


Gutenberg Literary Archive Foundation
The Project Gutenberg Literary Archive Foundation is a non-profit
501(c)(3) educational corporation organized under the laws of the
state of Mississippi and granted tax exempt status by the Internal
Revenue Service. The Foundation’s EIN or federal tax identification
number is 64-6221541. Contributions to the Project Gutenberg
Literary Archive Foundation are tax deductible to the full extent
permitted by U.S. federal laws and your state’s laws.

The Foundation’s business office is located at 809 North 1500 West,


Salt Lake City, UT 84116, (801) 596-1887. Email contact links and up
to date contact information can be found at the Foundation’s website
and official page at www.gutenberg.org/contact

Section 4. Information about Donations to


the Project Gutenberg Literary Archive
Foundation
Project Gutenberg™ depends upon and cannot survive without
widespread public support and donations to carry out its mission of
increasing the number of public domain and licensed works that can
be freely distributed in machine-readable form accessible by the
widest array of equipment including outdated equipment. Many
small donations ($1 to $5,000) are particularly important to
maintaining tax exempt status with the IRS.

The Foundation is committed to complying with the laws regulating


charities and charitable donations in all 50 states of the United
States. Compliance requirements are not uniform and it takes a
considerable effort, much paperwork and many fees to meet and
keep up with these requirements. We do not solicit donations in
locations where we have not received written confirmation of
compliance. To SEND DONATIONS or determine the status of
compliance for any particular state visit www.gutenberg.org/donate.

While we cannot and do not solicit contributions from states where


we have not met the solicitation requirements, we know of no
prohibition against accepting unsolicited donations from donors in
such states who approach us with offers to donate.

International donations are gratefully accepted, but we cannot make


any statements concerning tax treatment of donations received from
outside the United States. U.S. laws alone swamp our small staff.

Please check the Project Gutenberg web pages for current donation
methods and addresses. Donations are accepted in a number of
other ways including checks, online payments and credit card
donations. To donate, please visit: www.gutenberg.org/donate.

Section 5. General Information About


Project Gutenberg™ electronic works
Professor Michael S. Hart was the originator of the Project
Gutenberg™ concept of a library of electronic works that could be
freely shared with anyone. For forty years, he produced and
distributed Project Gutenberg™ eBooks with only a loose network of
volunteer support.
Project Gutenberg™ eBooks are often created from several printed
editions, all of which are confirmed as not protected by copyright in
the U.S. unless a copyright notice is included. Thus, we do not
necessarily keep eBooks in compliance with any particular paper
edition.

Most people start at our website which has the main PG search
facility: www.gutenberg.org.

This website includes information about Project Gutenberg™,


including how to make donations to the Project Gutenberg Literary
Archive Foundation, how to help produce our new eBooks, and how
to subscribe to our email newsletter to hear about new eBooks.

You might also like