Full download Dynamic SQL: Applications, Performance, and Security in Microsoft SQL Server - Second Edition Edward Pollack pdf docx
Full download Dynamic SQL: Applications, Performance, and Security in Microsoft SQL Server - Second Edition Edward Pollack pdf docx
com
https://ebookmeta.com/product/dynamic-sql-applications-
performance-and-security-in-microsoft-sql-server-second-
edition-edward-pollack/
OR CLICK HERE
DOWLOAD NOW
https://ebookmeta.com/product/expert-performance-indexing-in-azure-
sql-and-sql-server-2022-fourth-edition-edward-pollack/
ebookmeta.com
https://ebookmeta.com/product/scholarly-research-in-music-shared-and-
disciplinary-specific-practices-2nd-edition-sang-hie-lee/
ebookmeta.com
Scientific American Mind Scientific American
https://ebookmeta.com/product/scientific-american-mind-scientific-
american/
ebookmeta.com
https://ebookmeta.com/product/the-world-of-states-2nd-edition-john-l-
campbell/
ebookmeta.com
Nolo's Encyclopedia of Everyday Law: Answers to Your Most
Frequently Asked Legal Questions, 12th Edition The Editors
Of Nolo The Editors Of Nolo
https://ebookmeta.com/product/nolos-encyclopedia-of-everyday-law-
answers-to-your-most-frequently-asked-legal-questions-12th-edition-
the-editors-of-nolo-the-editors-of-nolo/
ebookmeta.com
Dynamic SQL
Applications, Performance, and Security
in Microsof t SQL Server
—
Second Edition
—
Edward Pollack
Dynamic SQL
Applications, Performance, and
Security in Microsoft SQL Server
Second Edition
Edward Pollack
Dynamic SQL: Applications, Performance, and Security in Microsoft SQL Server
Edward Pollack
Albany, NY, USA
Introduction������������������������������������������������������������������������������������������������������������xix
v
Table of Contents
vi
Table of Contents
vii
Table of Contents
viii
Table of Contents
Cardinality��������������������������������������������������������������������������������������������������������������������������������� 233
Statistics������������������������������������������������������������������������������������������������������������������������������ 234
Sys.dm_db_stats_properties���������������������������������������������������������������������������������������������� 244
Trace Flag 2371������������������������������������������������������������������������������������������������������������������� 245
Back to Dynamic SQL���������������������������������������������������������������������������������������������������������� 246
Query Hints������������������������������������������������������������������������������������������������������������������������������� 247
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 254
Cleanup������������������������������������������������������������������������������������������������������������������������������������� 254
ix
Table of Contents
x
Table of Contents
Index��������������������������������������������������������������������������������������������������������������������� 487
xi
About the Author
Edward Pollack has over 18 years of experience in database
and systems administration and architecture, developing a
passion for performance optimization and making things
go faster. He has spoken at many SQL Saturdays, 24 Hours
of PASS, and PASS Summit. This led him to organize SQL
Saturday Albany, which has become an annual event for
New York’s Capital Region.
In his free time, Ed enjoys video games, sci-fi & fantasy,
traveling, and cooking exceptionally spicy foods. He lives in
the subarctic icescape of Albany, NY with his wife Theresa,
his sons Nolan and Oliver, and an impressive collection of
video game-related plushies and figures.
xiii
About the Technical Reviewer
Kathi Kellenberger is the editor of Simple-Talk at Redgate Software, and Data Platform
MVP with over 20 years experience working with SQL Server. She is the author of several
books, including Beginning T-SQL, Beginning Reporting Services, and Expert T-SQL
Window Functions. When she is not working, she enjoys spending time with friends and
family, singing, and climbing the stairs of tall buildings.
xv
Acknowledgments
The SQL Server community is vast, made up of user groups, companies, professionals,
colleges, and organizations that create a network of like-minded individuals all looking
to further their knowledge, while at the same time helping others.
My interest in database administration was borne of some masochistic curiousity,
but the resources to learn, grow, and share that knowledge were made possible by
more people than I can count, each of whom has volunteered countless hours for the
betterment of others.
Thank you to the Professional Association of SQL Server; the Capital Area SQL Server
Group and its founders, Dan Bowlin and Joe Barth; to Autotask, a company that has
given me great amounts of professional freedom to explore database technologies in my
free time; Matt Slocum for organizing and letting me be a part of SQL Saturday Rochester
(the first I spoke at); APress for the opportunity to write and support throughout the
process; SQL Shack for standing behind my writing for years; my friends, who are always
there for me, no matter what life has thrown at us; to the many volunteers who organize,
speak, write, blog, and otherwise improve the world in their free time; and to my family
for having immense patience when I've come up with crazy ideas like this one.
xvii
Introduction
Dynamic SQL is a tool that is often described in bits and pieces, when a need for code
arises and time is limited. This book is an opportuntiy to put as many of those fragments
as possible together into a meaningful journey, from defining the technology to delving
into its deepest and most complex aspects. This is a dive into many topics that are
extremely important when working with any database. We will intentionally delve
deeper into performance optimization, application development, and security than may
seem necessary.
xix
Introduction
Intended Audience
Anyone with a healthy interest in database administration or development can benefit
from the topics covered within this book. Each chapter starts out with basic definitions
and examples, providing an easy entry point for professionals with any level of
experience. We transition into more advanced techniques, allowing you to not only learn
the basics of an important subject, but also gain access to scripts and ideas that could be
tested and used to solve problems you may face in your everyday experiences.
If you have a particular interest in database security or optimziation, then you will
appreciate the focus on these topics in each chapter. SQL Injection gets an exhaustive
review, with many different aspects and examples presented to ensure a thorough
explanation of this important topic! Every chapter, regardless of topic, will reference
performance whenever possible. It is an oft-made mistake that a database is designed
with little data and few users, ignoring the possibility that it will one day grow into a
behemoth. Reminders are placed throughout this book to consider query performance
at all times, even when performance may seem “good enough.”
xx
CHAPTER 1
A Simple Example
Starting with a very simple select statement, we will build a starting point for
understanding dynamic SQL:
This statement returns 10 rows from the table Person.Person, including all columns
in the table. What if we wanted to select data from a table, but did not know the name
of the table until runtime? How would we substitute the variable table name into our
1
© Edward Pollack 2019
E. Pollack, Dynamic SQL, https://doi.org/10.1007/978-1-4842-4318-3_1
Chapter 1 What Is Dynamic SQL?
T-SQL? Before answering that question, let’s introduce dynamic SQL by simply rewriting
the preceding query so that we are executing it as a character string, rather than standard
T-SQL:
The dynamic SQL command string is treated by SQL Server as a stored procedure
when parentheses are not included. Leave them out and you’ll be unable to execute your
SQL string, receiving an error similar to the preceding one.
2
Chapter 1 What Is Dynamic SQL?
For consistency and reliability, use NVARCHAR(MAX) as the data type for your
dynamic SQL command strings.
It may be tempting to use VARCHAR or use a smaller size string to save computing
resources, but as these are scalar variables, the memory used is relatively small and
very temporary. A 10,000 character NVARCHAR string would cost 20KB, whereas the
VARCHAR version would cost 10KB. The difference is minimal and will not have an
impact on any modern computing system. This logic should not be applied to tables,
where computing resources are multiplied by row counts, and additional storage
systems are involved.
3
Chapter 1 What Is Dynamic SQL?
The benefit of storing our T-SQL command as a string is that we are free to use any
string manipulation commands on it, building it in one or many steps. Now to tackle our
original problem: how to select data from a table that is not defined until runtime. To
accomplish this, we remove Person.Person from the string and replace it with a variable
that we define as shown previously:
The variable @table_name stores the name of the table we wish to query.
Commonly, this would be passed in as a parameter, either from other stored
procedures, or an application that calls this directly. By building it into @sql_command,
we gain the flexibility of querying any table we wish, without hard-coding it ahead
of time. While this is a trivial example (how often will we want to select data in this
fashion?), it provides the basis for thousands of applications, each of which can save
immense time, resources, and complexity. Before diving further into the details of
dynamic SQL and its many uses, let’s look at a more practical (and more complex)
example of dynamic SQL in action.
4
Chapter 1 What Is Dynamic SQL?
This T-SQL will back up the AdventureWorks2014 database to the SQLBackups folder
on the E drive, using compression. If we want to perform a custom database backup on
a subset of databases that all begin with the text “AdventureWorks,” we would need to
build T-SQL that could adapt to collect a list of all databases with that name, and then
perform backups on each of them separately. The following T-SQL shows one way that
this could be accomplished, using dynamic SQL.
Listing 1-2. Dynamic SQL Built to Back Up All Databases Starting with
“AdventureWorks”
DECLARE @database_list TABLE
(database_name SYSNAME);
WHILE @@FETCH_STATUS = 0
BEGIN
SELECT @sql_command = '
BACKUP DATABASE [' + @database_name + ']
TO DISK="E:\SQLBackups\' + @database_name + '.bak"
WITH COMPRESSION;'
5
Chapter 1 What Is Dynamic SQL?
EXEC (@sql_command);
CLOSE database_cursor;
DEALLOCATE database_cursor;
This T-SQL is certainly more complex than the first backup statement that we
looked at. Let’s break it apart in order to understand what is going on here, and why it
works. We can then focus on the dynamic SQL that provides the backbone of this set of
statements.
3. Build a dynamic SQL command string that takes into account the
current database name.
Much of this example is setup for the loop. The critical portion is where we substitute
the database name and backup file name with @database_name. This allows us to
generate a backup statement that will not only back up each database, regardless of how
6
Chapter 1 What Is Dynamic SQL?
many there are, but will name the backup file using that name. We could just as easily
append additional information onto the file name, such as the date, time, or server
name, if it were important.
Backups are a perfect use of dynamic SQL, as we can continue to customize and add
time-saving functionality into our code, such as:
Customizable Everything
Adding joins or WHERE clauses are only the beginning. With dynamic SQL, any
statement can be customized to provide greater flexibility to your code. Want to group
by a column based on a dynamic search? The solution is to write the GROUP BY clause
7
Chapter 1 What Is Dynamic SQL?
as dynamic SQL, altering it as needed to fit the needs of each specific situation. Want to
generate row numbers for a data set, but won’t know which columns to partition by or
order by until runtime? No problem!
Our preceding example illustrated how we could use dynamic SQL to customize a
backup operation, and customize the name of the backup file. Any conceivable T-SQL
statement can be altered to utilize dynamic SQL, and in doing so, allow for greater
flexibility in any number of day-to-day challenges.
ORM (object-relational mapping) software can allow for similar levels of customization,
but not all companies can (or want) to use software that automatically generates T-SQL,
as performance and complexity can quickly become overwhelming. Like any querying
application, choosing the correct tool is essential to scalability and performance.
Using dynamic SQL, we can generate any amount of commands or text without
limit. SQL Server will not tire of this process, no matter how dull it may seem. This is an
opportunity to automate tedious tasks and reduce operator intervention in those that
would end up being busy work. The result is that our jobs become easier, more fun, and
we can focus on more important tasks that demand our attention!
9
Chapter 1 What Is Dynamic SQL?
10
Chapter 1 What Is Dynamic SQL?
11
Chapter 1 What Is Dynamic SQL?
SQL Server functions must be deterministic. Inputs and outputs must be in the
form given in the function definition. Dynamic SQL by nature is nondeterministic, and
therefore cannot be used within functions.
Document Thoroughly
This is the mantra that is repeated to anyone who has ever written a line of code, a script,
or a nontechnical process. Your documentation explains how your code works, why it is
written as it is, and serves as a guide when changes will inevitably be made. T-SQL that
12
Chapter 1 What Is Dynamic SQL?
may not normally warrant documentation will become harder to read when dynamic
SQL is applied. Consider creating additional documentation to supplement this added
complexity.
The first and simplest way to document your work is to include a header at the top
of your file. This header provides basic information on who created this code, some
revision notes, its purpose, and a quick overview of how it works. Understanding the
reasons behind why a stored procedure was created can be as useful as knowing how it
works. More importantly, it is possible to discern the function of code by reading through
it and scratching one’s head a bit. It isn’t possible to figure out the original request
that spurred the creation of that code without either having some existing application
knowledge that others may not have or asking other developers for help.
Consider the following header for a simple backup script:
1. The date that this code was written, to provide context into when
it came about
3. Background into why this was written and the problem that was
being addressed
13
Chapter 1 What Is Dynamic SQL?
This short documentation block answers most of the common questions that a
developer may have about your code. The things we consider obvious while writing
T-SQL may not be so obvious to someone else reading this years later. Our own code
is always easier to read than that of others, and this is easy to forget when buried in
development projects. As time passes, though, even our own code can be hard to
understand as we become more detached from the details of how we wrote it.
When writing code that involves dynamic SQL, we must consider documenting
thoroughly, but also not go overboard and explain every single line of T-SQL. Let’s take
our backup routine from earlier and add some meaningful documentation to it.
-- This will temporarily store the list of databases that we will back up
below.
DECLARE @database_list TABLE
(database_name SYSNAME);
14
Exploring the Variety of Random
Documents with Different Content
concrete work; except that the drain pipe used will be paid for per
linear foot at the price named in the contract which price shall cover
the cost of furnishing and putting the pipe in place complete.
PART II
INSTRUCTIONS TO INSPECTORS ON
STREET PAVING WORK
INTRODUCTORY NOTE
GENERAL
1. The chief duty of the inspector is to see that the work to which
he is assigned shall be carried out in full and strict accordance with
the plans and specifications therefor, and with such additional
instructions as may from time to time be given by the engineer.
2. These instructions are intended to supplement but in no case to
take the place of the specifications for the work, which must be fully
and strictly complied with, unless they are changed or modified by
the engineer.
3. Wherever the words “the engineer” are used in these
instructions they refer to the chief engineer in charge of the work for
the municipality, or his authorized deputies or agents.
Wherever the words “the contractor” are used they refer to the
person, or firm, or corporation under contract to perform the work to
which you are assigned, or his agents or employees engaged upon the
work.
4. You will report to and be under the exclusive direction and
control of the engineer.
5. Upon being assigned to any work you will obtain copies of the
plans and specifications under which it is to be done, and will
carefully read and acquaint yourself with all their provisions and
requirements. If any part of these plans and specifications are not
clearly understood by you, you will ask the engineer for explanations
and instructions, and will be governed thereby. Failure to
understand or to be familiar with the plans and specifications will in
no case be accepted as an excuse for not complying with and
enforcing them.
You will also obtain, study and familiarize yourself with all the
blank forms, reports, etc., that are to be used by you on the work, so
that they may be correctly utilized; you will also obtain a proper
supply of such apparatus, tools, stationery, etc., as you will need
upon the work.
6. In inspecting any work done under contract you are to assume
that the contractor is bound to carry out in good faith the plans and
specifications attached to his contract, and that he may be, and must
be, held to a strict compliance with them unless you receive
instructions to the contrary from the engineer. You will be held
responsible for the enforcement of these plans and specifications so
far as they relate to the doing of the work.
7. In case the contractor or his agents shall neglect or refuse to
comply with the plans and specifications or to perform the work in a
proper manner, or in accordance with the instructions of the
engineer, you will direct him to suspend the particular work in fault
and will report all the facts promptly to the engineer and await his
instructions, which, when received, you will proceed to enforce.
8. You will be expected to be upon the work at all times when work
is in progress, whether during ordinary working or office hours, or
not. But in case the contractor shall work continuous day and night
forces, or otherwise so conduct the work as to require the presence of
an inspector for unusual or unreasonable hours of service, you will
notify the engineer and ask instructions or assistance. If for any
reason you are to be unable to be present whenever work is in
progress you will promptly notify the engineer in time to enable him
to supply a substitute.
9. All reports and records required of you by the engineer must be
promptly made up and forwarded to him at the time and in the
manner he may direct. You will promptly acknowledge in person or
writing any instructions received from the engineer and in case such
instructions are not clearly understood by you, you will ask for
explanation or advice.
You will keep a notebook or diary in which all occurrences or
matters of interest relating to the work will be recorded each day,
which book will be delivered to the engineer on the completion of the
work, or whenever your connection therewith may end. All diaries,
notebooks and records kept on the work are the property of the city.
10. While your first duty is to see that the work is done in
accordance with the plans and specifications, you will, so far as
consistent with this duty, be considerate of the interests of the
contractor and facilitate his work as much as practicable. Materials
should be inspected promptly upon delivery and in such a manner as
not to delay or discommode the contractor more than is necessary.
Errors, defects or delinquencies in the work should be detected and
called attention to promptly, so as to avoid tearing up and re-
construction as far as practicable.
11. Orders and instructions should be given to the contractor or his
foremen or representatives on the work and not to the laborers,
unless in urgent cases.
12. You shall not at any time, before, during, or after the
completion of the work, ask or accept from the contractor or any of
his agents or employees, or from any other person whom you may
have reason to believe is acting for the contractor, any money, gifts,
gratuities or other considerations of value, whether as compensation
for services rendered him or otherwise. The penalty for violation of
this rule will be dismissal from the service followed by such legal
prosecution as the engineer may direct. This rule does not apply to
the ordinary small courtesies common between gentlemen associated
in business.
13. It is a condition of your employment that your services shall be
loyal to the interests of the municipality, efficient, and satisfactory to
the engineer, and that whenever in his opinion your service falls
short of this standard he may dismiss you at any time, without
previous notice.
STREET PAVING WORK
CONCRETE FOUNDATIONS
1 nest of standard sieves, Nos. 10, 30, 50, 80, 100 and 200
2 thermometers for sand
1 tank thermometer
2 standard flow-plates and one dozen cartridges for same
1 balance for weighing sand
6 dishes, glass or porcelain, 4 inches in diameter.
30. The more important things for the Plant Inspector to watch
during the manufacture of asphalt paving mixture are: