SlideShare a Scribd company logo
Programming Microsoft Sql Server 2000 With
Microsoft Visual Basic Net 1st Edition Dobson
download
https://ebookbell.com/product/programming-microsoft-sql-
server-2000-with-microsoft-visual-basic-net-1st-edition-
dobson-55141988
Explore and download more ebooks at ebookbell.com
Here are some recommended products that we believe you will be
interested in. You can click the link to download.
Programming Microsoft Sql Server 2000 With Xml Graeme Malcolm
https://ebookbell.com/product/programming-microsoft-sql-
server-2000-with-xml-graeme-malcolm-926310
Microsoft Sql Server 2000 Programming By Example Carlos Rojas
https://ebookbell.com/product/microsoft-sql-server-2000-programming-
by-example-carlos-rojas-976716
Programming Microsoft Sql Server 2008 Leonard Lobel Andrew J Brust
https://ebookbell.com/product/programming-microsoft-sql-
server-2008-leonard-lobel-andrew-j-brust-1232300
Inside Microsoft Sql Server 2008 Tsql Programming Prodeveloper 1st
Edition Itzik Bengan
https://ebookbell.com/product/inside-microsoft-sql-server-2008-tsql-
programming-prodeveloper-1st-edition-itzik-bengan-2112660
Beginning Microsoft Sql Server 2008 Programming Robert Vieira
https://ebookbell.com/product/beginning-microsoft-sql-
server-2008-programming-robert-vieira-5468682
Professional Microsoft Sql Server 2008 Programming Robert Vieira
https://ebookbell.com/product/professional-microsoft-sql-
server-2008-programming-robert-vieira-5473568
Beginning Microsoft Sql Server 2008 Programming Robert Vieira
https://ebookbell.com/product/beginning-microsoft-sql-
server-2008-programming-robert-vieira-61013860
Inside Microsoft Sql Server 2005 Tsql Programming Itzik Bengan
https://ebookbell.com/product/inside-microsoft-sql-server-2005-tsql-
programming-itzik-bengan-917874
Microsoft Sql Server 2005 Programming For Dummies Andrew Watt
https://ebookbell.com/product/microsoft-sql-server-2005-programming-
for-dummies-andrew-watt-975328
Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson
Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson
Programming Microsoft® SQL Server™ 2000 with Microsoft Visual
Basic® .NET
Foreword
Acknowledgments
Introduction
Who’s the Book For?
What’s Special About This Book?
How’s the Book Organized?
System Requirem ents
Sample Files
Support
1. Getting Started with Visual Basic .NET for SQL Server 2000
Visual Studio .NET, the Visual Basic .NET IDE
An Overview of ADO.NET Capabilities
A Starter ADO.NET Sam ple
Using Query Analyzer
2. Tables and Data Types
Chapter Resources
Data Types for Tables
Scripting Tables
3. Program m ing Data Access with T-SQL
I ntroduction to Data Access with T-SQL
Aggregating and Grouping Rows
Processing Dates
Joins and Subqueries
4. Program m ing Views and Stored Procedures
I ntroduction to Views
Creating and Using Views
Views for Remote and Heterogeneous Sources
I ntroduction to Stored Procedures
Creating and Using Stored Procedures
Processing Stored Procedure Outputs
I nserting, Updating, and Deleting Rows
Programm ing Conditional Result Sets
5. Program m ing User-Defined Functions and Triggers
I ntroduction to User-Defined Functions
Creating and I nvoking Scalar UDFs
Creating and I nvoking Table-Valued UDFs
I ntroduction to Triggers
Creating and Managing Triggers
6. SQL Server 2000 XML Functionality
Overview of XML Support
XML Formats and Schemas
URL Access to SQL Server
Template Access to SQL Server
7. SQL Server 2000 Security
Overview of SQL Server Security
I ntroduction to Special Security I ssues
Samples for Logins and Users
Samples for Assigning Perm issions
8. Overview of the .NET Fram ework
An I ntroduction to the .NET Fram ework
An Overview of ASP.NET
XML Web Services
9. Creating Windows Applications
Getting Started with Windows Forms
Creating and Using Class References
I nheriting Classes
Programm ing Events
Exception Handling for Run-Tim e Errors
10. Programm ing Windows Solutions with ADO.NET
An Overview of ADO.NET Objects
Making Connections
Working with Command and DataReader Objects
DataAdapters , Data Sets, Forms, and Form Controls
Modifying, Inserting, and Deleting Rows
11. Programm ing ASP.NET Solutions
Review of ASP.NET Design I ssues
Creating and Running ASP.NET Solutions
Session State Management
Data on Web Pages
Validating the Data on a Web Page
12. Managing XML with Visual Basic .NET
SQL Server Web Releases
Overview of XML Technologies
Generating XML Documents with the .NET Framework
Dynam ically Setting an XML Result Set
The I nterplay Between XML and Data Sets
Creating HTML Pages with XSLT
13. Creating Solutions with XML Web Services
Overview of Web services
A Web Service to Return a Com puted Result
A Web Service to Return Values from Tables
The SQL Server 2000 Web Services Toolkit
More on Populating Controls with Web Services
About the Author
Forew ord
During m y five years at Microsoft, I ’ve been helping developers understand
technologies such as Microsoft Visual Studio, Microsoft SQL Server, and Microsoft
Office Developer. During the past two years, I have worked on the Microsoft
Office XP Visual Basic Language Reference, and now, the MSDN Office Developer
Center. I n the m onthly column on MSDN, Office Talk, I have written articles to
help Office developers understand the .NET platform and how it affects their
current and future development efforts.
As I write this foreword to Rick Dobson’s book on programm ing Microsoft SQL
Server solutions with Microsoft Visual Basic .NET, I think back to my own
experiences developing software applications with Visual Basic. My first
experience with Visual Basic was learning the language using version 3.0. I
rem ember picking up m y first Visual Basic beginner’s book and being excited as I
developed my first few “Hello, World” applications. I couldn’t believe how quick
and easy it was to develop software applications that operated sim ilarly to other
popular shareware program s of that tim e.
However, during that time I also discovered som e of the shortcom ings of Visual
Basic as an enterprise-level development language. It was then that I turned my
attention to C+ + . I rem ember being very frustrated at trying to learn the
language, trying to understand concepts such as pointers, m em ory allocation,
and true object-oriented programm ing. I took classes on C+ + at the local
university, but I got even m ore frustrated having to wait m onths until I was
taught how to create the sim plest Microsoft Windows form, something I did in
just a couple of m inutes using Visual Basic. I n my frustration, I gave up trying to
learn C+ + and have been using Visual Basic to develop software applications ever
since.
As each new version of Visual Basic was released, I readied myself to learn new
software developm ent technologies. First it was ActiveX control development.
Then it was calling the Windows API . Next it was DHTML Applications. Then it was
database developm ent using Microsoft SQL Server. I t always seem ed as though I
had to learn a new language and a new developm ent paradigm for every new
technology that came along. I kept thinking that there had to be an easier and
more unified approach.
Well, now we’ve reached the advent of the Microsoft .NET platform , and with it, a
revolution in the Visual Basic language, Microsoft Visual Basic .NET. I believe that
Visual Basic .NET will provide software developers with new opportunities for
quickly and easily designing integrated software applications that connect
businesses and individuals anytime, anywhere, and on virtually any software
device. With advances in the Visual Basic .NET language, Visual Basic .NET
developers will finally be on a par with their C+ + and C# counterparts,
participating in many high-end developm ent projects. With Visual Studio .NET
features such as cross-language debugging, along with Visual Basic .NET
conformance to the com mon type system and the com mon language runtime,
organizations can drive down their development costs by tapping into the wide
range of skills that Visual Basic .NET developers now possess.
True object-oriented programm ing is now available in Visual Basic .NET, including
features such as inheritance and m ethod overloading. I t’s now simpler to call the
Windows API by using the .NET Fram ework Class Libraries. Web application
developm ent is now as easy as developing Windows form s–based applications.
Database application developm ent is made easier by uniting disparate data object
libraries such as DAO, RDO, OLE DB, and ADO under ADO.NET, utilizing the
power of XML to consume and transm it relational data over com puter networks.
And a new technology, XML Web services, allows Visual Basic .NET developers to
host their software applications’ logic over the Web. Additionally, a big issue for
software developers today is that of software application deploym ent and
versioning. I f you don’t agree, just ask any software developer about “DLL hell,”
and you’re bound to get an earful. For m any .NET applications, the .NET platform
features “copy and paste” or XCOPY deploym ent. (Users simply copy your
application files from the source media to any single directory and run the
application.) And because .NET no longer relies on the registry, virtually all DLL
compatibility issues go away.
With this book, Rick aim s to give you the skills you need to program SQL Server
solutions with Visual Basic .NET. I know you will find Rick’s book helpful. Rick
brings his experience to bear from three previous books: Programm ing Microsoft
Access Version 2002 (Microsoft Press, 2001), Program m ing Microsoft Access 2000
(Microsoft Press, 1999), and Professional SQL Server Development with Access
2000 (Wrox Press I nc., 2000). Rick also brings his experience of leading a
successful nationwide sem inar tour. More important, I know you will enjoy Rick’s
book because of his deep interest in Visual Basic .NET and SQL Server, and in
helping you, the professional developer, understand and apply these technologies
in your daily software application developm ent projects.
Paul Cornell MSDN Office Developer Center
http: / / msdn.m icrosoft.com/ officeMicrosoft Corporation February 2002
Acknow ledgm ents
This section offers me a chance to say thank you to all who helped make this
book possible. I wish to offer special recognition to five support resources.
First, the folks at Microsoft Press have been fantastic. Dave Clark, an acquisitions
editor, selected me to write the book just months after I completed another book
for Microsoft Press. Dick Brown, m y project editor, staunchly stood up for his
perception of how to m ake the book’s organization and content clear to you
without being petty or boring to m e. Dick also lightened my load substantially by
showing a real knack for editing my text without distorting the original intent.
When Dick was especially busy, he handed off some of his load to Jean Ross, who
also did an adm irable job. Others at Microsoft Press who contributed to my well-
being in one way or another include Aaron Lavin and Anne Hamilton.
Second, I had excellent working relations with several professionals within
Microsoft. Paul Cornell, a widely known technical editor at Microsoft, was kind
enough to share his insights on how to present .NET concepts compellingly. I
want to thank Paul especially for writing the Foreword to this book. Karthik
Ravindran served as the MSXML Beta Product Lead Engineer at Microsoft Product
Support Services during the time that I wrote this book. He provided valuable
technical content about the SQL Server 2000 Web releases. Other Microsoft
representatives providing moral and technical support for this book include
Richard Waym ire and Jan Shanahan.
Third, I want to express m y appreciation to the many readers, sem inar
attendees, and site visitors who took the time to tell m e what I did right or wrong
for them, and also to those who shared their technical support questions with me.
It is through this kind of feedback that I am able to know what’s important to
practicing developers. I encourage you to visit my m ain Web site
(http: / / www.programm ingmsaccess.com) and sign the guest book. The entry
form includes space for you to leave your evaluation of this book or your question
about a topic covered in the book. I prom ise to do my best to reply personally. I n
any event, I definitely read all m essages and use them so that I can serve you
better with future editions of this, and other, books.
Fourth, I want to tell the world how grateful I am to my wife, Virginia. Without
Virginia’s warm support, love, and care, this book would be less professional. She
relieves m e of nearly every responsibility around the house when I undertake a
book project. In addition, she offers strategic advice on the issues to address and
their style of coverage. When I run out of tim e, she even pitches in with the
proofreading.
Fifth, it is important for me to give praise and glory to my Lord and Savior, Jesus
Christ, who I believe gave m e the strength and wisdom to write this book. I n
addition, He gave m e health during the long gestation period that resulted in the
birth of this book. I t is my prayer that the book prove to be a blessing to you.
I ntroduction
Anyone who buys a book—or considers buying it—wants to know who the book is
for, what sets it apart from others like it, and how the book is organized. This
introduction covers those three questions, and it also discusses system
requirem ents, sample files, and support.
• First, w ho is the book for? There are at least two answers to this
question. One answer is that the book targets professional developers
(and others aspiring to be professional developers). The second group the
book addresses is those who want to build full-featured, secure SQL
Server solutions with Visual Basic .NET.
• Second, w hat’s special about the book? I hope you com e to believe
that the m ost important answer to this question is that the book
considered quality and depth of coverage more important than rushing to
market. The book will arrive on bookshelves m ore than three months after
the official release of the .NET Framework. I t is my wish that you derive
value from the extra time taken to develop the m any code samples and
the in-depth discussions of advanced topics, such as class inheritance,
ASP.NET, and XML Web services.
• Third, how is the book organized? The short answer is that there are
two main sections. One section introduces SQL Server concepts as it
dem onstrates T-SQL (Transact SQL) programming techniques. After
conveying SQL Server basic building blocks in the first part, the second
part reveals how to put those parts together with Visual Basic .NET and
related technologies into SQL Server solutions for handling common
database chores.
The three support item s include a brief description of the book’s companion CD
and how to use it, Microsoft Press Support I nformation for this book, and a
summary of system and software requirem ents for the sample code presented in
the book.
W ho’s the Book For?
This book targets professional Visual Basic and Visual Basic for Applications
developers. From my seminar tours and Web sites
(http: / / www.programm ingmsaccess.com and http: / / www.cabinc.net), I know
that these professionals are driven by a passion to deliver solutions to their
clients through applying the m ost innovative technologies their clients will accept.
In-house developers are the go-to persons for getting results fast— particularly for
custom in-house systems and databases. I ndependent developers specialize in
serving niche situations that can include under-served business needs and work
overflows. I n both cases, these professionals need training m aterials that address
practical business requirem ents while showcasing innovative technologies without
wasting their tim e. This book strives to serve this broad need in two specific
areas.
This book is for developers looking for code samples and step-by-step instructions
for building SQL Server 2000 solutions with Visual Basic .NET. The book focuses
on the integration of SQL Server 2000 with .NET technologies tapped via Visual
Basic .NET. I t is my firm belief that you cannot create great SQL Server solutions
in any programm ing language without knowing SQL Server. Therefore, this book
goes beyond traditional coverage of SQL Server for Visual Basic developers. You’ll
learn T-SQL program m ing techniques for data access, data manipulation, and
data definition. A whole chapter equips you to secure your SQL Server solutions.
In addition, there’s plenty of content in this book on Visual Basic .NET and related
technologies, such as ADO.NET, ASP.NET, XML (Extensible Markup Language),
and XML Web services. The presentation of these technologies demonstrates
coding techniques and explores concepts that equip you to build better solutions
with SQL Server 2000 databases. I n addition, the book highlights innovations
introduced through the Web releases for SQL Server 2000 that integrate SQL
Server 2000 tightly with Visual Basic .NET.
This isn’t a book about XML, but three of the book’s 13 chapters focus in whole or
in part on XML. Therefore, those seeking practical dem onstrations of how to use
XML with SQL Server and Visual Basic .NET will derive value from this book. I f
you have looked at any of the computer magazines over the past couple of years,
you know that XML is coming to a solution near you. However, the rapid pace of
XML innovation m ay have dissuaded som e from jum ping on the bandwagon while
they wait to see what’s going to last and what’s just a fad. I n the book’s three
chapters on XML technology, you’ll learn about XML documents, fragm ents, and
formatting as well as related technologies, such as XPath (XML Path Language)
queries, XSLT (Extensible Stylesheet Language Transformation), and WSDL (Web
Services Description Language).
W hat’s Special About This Book?
There are several features that make this book stand apart from the flood of
books on .NET. One of the m ost important of these is that this book didn’t rush to
market but rather shipped m onths after the release of the .NET Framework. This
allowed me enough tim e to filter, exam ine, and uncover what were the m ost
useful and innovative features for Visual Basic .NET developers building SQL
Server solutions. For example, the book includes a whole chapter on creating
solutions with XML Web services. That chapter includes two major sections on the
SQL Server 2000 Web Services Toolkit, which didn’t ship until the day of the .NET
Framework release.
The .NET Framework content is at a professional level, but it isn’t just for techies.
This book doesn’t assume any prior knowledge of the .NET Framework. I t does
assume that you get paid for building solutions programmatically and that at least
some of those solutions are for SQL Server databases. Therefore, the book
explains basic .NET concepts and dem onstrates how to achieve practical results
with those concepts through a huge collection of .NET code samples.
This book is about building solutions for SQL Server 2000. I include coverage of
the many special features that tie Visual Basic .NET and SQL Server 2000 closely
to one another. Although there is coverage of general .NET database techniques,
this book dives deeply into T-SQL programm ing techniques so that you can create
your own custom database objects, such as tables, stored procedures, views,
triggers, and user-defined functions. I n addition, there is separate coverage of
the XML features released with SQL Server 2000 as well as separate coverage of
the XML features in the first three Web releases that shipped for SQL Server
2000. There are num erous code samples throughout the book. These will equip
you to build solutions with Visual Basic .NET, T-SQL, and combinations of the two.
Finally, this book is special because of the unique experiences of its author, Rick
Dobson. I have trained professional developers in Australia, England, Canada,
and throughout the United States. This is my fourth book in four years, and you
can find my articles in popular publications and Web sites, such as SQL Server
Magazine and MSDN Online. As a Webmaster, my main site
(http: / / www.programm ingmsaccess.com) serves hundreds of thousands of
sessions to developers each year. I constantly exam ine their viewing habits at the
site to determ ine what interests them. I n addition, my site features scores of
answers to technical support questions subm itted by professional developers. My
goal in offering answers to these questions is to stay in touch with practicing
developers worldwide so that my new books address the needs of practicing,
professional developers.
How ’s the Book Organized?
There are two main parts to this book tied together by an introductory part. Part
II , the first main part, dwells on SQL Server techniques. Part I II builds on the
SQL Server background as it lays a firm foundation in .NET techniques for Visual
Basic .NET developers. Part I, the introductory part, demonstrates ways to use
SQL Server and Visual Basic .NET together.
Part I , I ntroduction
Part I , which includes only Chapter 1, has three main goals. First, it acquaints you
with the basics of Visual Basic .NET within Visual Studio .NET. You can think of
Visual Basic .NET as a major upgrade to the Visual Basic 5 or 6 that you are
probably using currently. This first section introduces some concepts that you will
find useful as you initially learn the landscape of Visual Basic .NET. The second
goal of Chapter 1 is to introduce ADO.NET. I f you think of Visual Basic .NET as a
major upgrade to Visual Basic 6, ADO.NET is m ore like a major overhaul of ADO.
In two sections, you get an introduction to ADO.NET classes— particularly as they
relate to SQL Server— and you get a chance to see a couple of beginner sam ples
of how to create SQL Server solutions with Visual Basic .NET and ADO.NET. The
third goal of the introductory part is to expose you to Query Analyzer. This is a
SQL Server client tool that ships with all comm ercial editions of SQL Server 2000.
You can think of it as an IDE for T-SQL code. Most of the book’s first part relies
heavily on T-SQL, and therefore having a convenient environment for debugging
and running T-SQL code is helpful. The final section of Chapter 1 addresses this
goal.
Part I I , SQL Server
Part I I consists of six relatively short chapters that focus substantially on
programm ing SQL Server 2000 with T-SQL. Chapter 2 and Chapter 3 introduce T-
SQL and SQL Server data types. I f you are going to program SQL Server and
create efficient, fast solutions, you m ust learn SQL Server data types, which is
one of the main points conveyed by Chapter 2. Many readers will gravitate to
Chapter 3 because it introduces core T-SQL program m ing techniques for data
access. You’ll apply the techniques covered in this chapter often as you select
subsets of rows and colum ns in data sources, group and aggregate rows from a
table, process dates, and join data from two or more tables. Chapter 3 also
considers special data access topics, such as outer joins, self joins and
subqueries.
The next pair of chapters in Part I I , Chapter 4 and Chapter 5, take a look at
programm ing database objects that you will use for data access and data
manipulation, such as views, stored procedures, user-defined functions, and
triggers. These database objects are im portant for many reasons, but one of the
most important is that they bundle T-SQL statements for their easy reuse. I t is
widely known that the best code is the code that you don’t have to write.
However, if you do have to write code, you should definitely write it just onc, and
then reuse it whenever you need its functionality. Stored procedures are
particularly desirable database objects because they save compiled T-SQL
statements that can deliver significant speed advantages over resubm itting the
same T-SQL statement for compilation each tim e you want to perform a data
access or data manipulation task. Chapter 4 and Chapter 5 are also important
because they convey T-SQL syntax for using parameters and conditional logic
that support dynam ic run-tim e behavior and user interactivity.
One of the m ost important features of SQL Server 2000 is its XML functionality.
Because XML as a topic is changing so rapidly, Microsoft adopted a strategy of
upgrading the SQL Server 2000 XML functionality through Web releases. Although
those with SQL Server 2000 can download the Web releases without charge from
the Microsoft Web site, the Web releases are fully supported. Chapter 6
introduces core XML functionality introduced with SQL Server 2000 as well as
functionality from the first two Web releases. I n particular, you can learn in this
chapter about I IS virtual directories as well as form ats for XML docum ents and
schemas. You also learn about templates in virtual directories that facilitate data
access and data manipulation tasks over the Web.
Chapter 7 closes out the SQL Server part of the book with an in-depth look at
programm ing SQL Server security. I n these tim es, security has grown into a
monum ental topic, and this chapter can keep you out of trouble by blocking
hackers from getting into or corrupting your database. You learn such topics as
how to create and manage different types of login and user accounts and how to
control the perm issions available to individual accounts as well as groups of
accounts. By learning how to script accounts and perm issions with T-SQL, you
simplify revising and updating security as conditions change (for exam ple, when
users leave the company or when new, sensitive data gets added to a table).
Part I I I , .NET
Chapter 8 starts the .NET part of the book with a review of selected .NET topics
that are covered in the initial look Chapter 1 offered at the .NET Fram ework. This
chapter provides an overview of the architecture for .NET solutions, and it drills
down on two topics: ASP.NET and XML Web services. The general purpose of this
chapter is the same as Chapter 1, which is to introduce concepts. The emphasis
in Chapter 8 isn’t how you do som ething, but rather what are the major
technologies enabling you to do som ething. Chapter 1 and Chapter 8 are both
relatively short chapters, but you may find them invaluable if you are the kind of
person who benefits from high-level overviews of a collection of topics.
Chapter 9 starts with a close exam ination of how to use Windows Form s with
Visual Basic .NET. I t then shifts its focus to a review of traditional class
processing concepts via Visual Basic .NET as an introduction to class inheritance,
a new object-oriented feature that makes its first appearance in Visual Basic with
Visual Basic .NET. Next the treatm ent of classes progresses to the handling of
built-in events as well as the raising of custom events. Finally the chapter closes
with an exam ination of the new exception handling techniques for processing run-
time errors.
Chapter 10 is a how-to guide for solutions to typical problems with ADO.NET.
Before launching into its progression of sam ples showing how to perform all kinds
of tasks, the chapter starts with an overview of the ADO.NET object m odel that
covers the main objects along with selected properties and m ethods for each
object. The how-to guide focuses on data access tasks, such as selecting rows
and columns from SQL Server database objects, as well as data manipulation
tasks, such as inserting, updating, and deleting rows in a table. Working through
the samples in the how-to guide offers a hands-on feel for using the
System .Data.SqlClient namespace elem ents to perform typical tasks.
Chapter 11 switches the focus to the Web by addressing the creation and use of
ASP.NET solutions. This chapter starts by introducing basic elem ents that you
need to know in order to use ASP.NET to create great Web solutions with Visual
Basic .NET. These include learning what happens as a page does a round-trip
from a browser to a Web server and back to the browser— particularly for data
associated with the page. Other prelim inary topics that equip you for building
professional Web solutions include running the same page in m ultiple browser
types and sniffing the browser for cases in which you want to send a page
optim ized for a specific kind of browser type. Managem ent of session state is a
major topic in the chapter, and you learn how to use enhancem ents to Session
variables for Web farms as well as the new view state variables, a non-server-
based technique for managing state in ASP.NET solutions. The last two sections in
the chapter deal with ADO.NET topics in ASP.NET solutions and the new
autom atic data validation features built right into ASP.NET.
The last two chapters in the book explore how XML interplays with Visual Studio
.NET and SQL Server 2000. For example, Chapter 12 exam ines special tools in
Visual Studio .NET to facilitate the design and editing of XML docum ents and
schemas. I n addition, you learn how to designate XPath queries that accept run-
time input for returning SQL Server result sets inside Visual Basic .NET programs.
The chapter dem onstrates techniques for processing the XML document
associated with all ADO.NET data set objects. I n the chapter’s last section, I
present a couple of code sam ples that illustrate how to program static HTML
pages based on XML documents with XSLT.
Chapter 13 drills down on XML Web services by dem onstrating several different
approaches for creating Web services as well as consum ing XML output from Web
services. Web services behave somewhat like COM objects in that you can set up
server applications for client applications. The server applications expose m ethods
to which the client applications can pass param eters. XML comes into play with
Web services in a couple of areas. First, Web services represent their inputs and
outputs via WSDL, an XML-based language that form ally describes an XML Web
service. Second, Web services return data to their clients as XML documents or
document fragm ents.
System Requirem ents
The requirem ents for this book vary by chapter. I developed and tested all
samples throughout this book on a com puter equipped with Windows 2000
Server, SQL Server Enterprise Edition, and the Enterprise Developer Edition of
Visual Studio .NET, which includes Visual Basic .NET. To use this book, you’ll need
to have Visual Basic .NET or Visual Studio .NET installed on your computer. (See
Chapter 1 for m ore information on versions of Visual Basic .NET and Visual Studio
.NET.) I n addition, you’ll need SQL Server 2000, and for som e of the chapters,
you’ll need SQL Server 2000 updated with Web releases 1, 2, and 3. Chapter 6
gives the URLs for downloading Web releases 1 and 2. Chapter 12 gives two
different URLs for downloading Web Release 3— one with the SQL Server 2000
Web Services Toolkit and the other without it.
For selected chapters, you can run the samples with less software or different
operating systems than the one that I used. For example, chapters 2 through 5
will run on any operating system that supports a comm ercial version of SQL
Server 2000, such as Windows 98 or a m ore recent Windows operating system.
Chapter 7 requires an operating system that supports Windows NT security, such
as Windows 2000 or Windows XP Professional. Chapter 6, Chapter 11, and
Chapter 13 require Microsoft I nternet Inform ation Services (I I S). I n addition,
Chapter 6 requires the installation of Web releases 1 and 2. For Chapter 11, your
system needs to m eet the m inim um requirem ents for ASP.NET. (See a note in the
“How Does ASP.NET Relate to ASP?” section of Chapter 8.) Several of the
samples in Chapter 1 3 require Web Release 3 and its associated SQL Server
2000 Web Services Toolkit.
Sam ple Files
Sample files for this book can be found at the Microsoft Press Web site, at
http: / / www.m icrosoft.com/ m spress/ books/ 5792.asp. Clicking the Com panion
Content link takes you to a page from which you can download the sam ples.
Supplem ental content files for this book can also be found on the book’s
companion CD. To access those files, insert the companion CD into your
computer’s CD-ROM drive and make a selection from the menu that appears. I f
the AutoRun feature isn’t enabled on your system (if a m enu doesn’t appear when
you insert the disc in your computer’s CD-ROM drive), run StartCD.exe in the root
folder of the com panion CD. I nstalling the sam ple files on your hard disk requires
approximately 15.3 MB of disk space. I f you have trouble running any of these
files, refer to the text in the book that describes these programs.
Aside from the sample files that this book discusses, the book’s supplem ental
content includes a stand-alone eBook installation that will allow you to access an
electronic version of the print book directly from your desktop.
Support
Every effort has been m ade to ensure the accuracy of this book and the contents
of the companion CD. Microsoft Press provides corrections for books through the
World Wide Web at the following address:
http: / / www.m icrosoft.com/ m spress/ support
To connect directly to the Microsoft Press Knowledge Base and enter a query
regarding a question or an issue that you may have, go to:
http: / / www.m icrosoft.com/ m spress/ support/ search.asp
If you have comments, questions, or ideas regarding this book or the companion
content, or questions that are not answered by querying the Knowledge Base,
please send them to Microsoft Press via e-mail to:
mspinput@m icrosoft.com
Or via postal mail to:
Microsoft Press Attn: Programm ing Microsoft SQL Server 2000 with Microsoft
Visual Basic .NET Editor One Microsoft Way Redm ond, WA 98052-6399
Please note that product support is not offered through the above mail address.
For product support information, please visit the Microsoft Support Web site at:
http: / / support.m icrosoft.com
Chapter 1. Getting Started w ith Visual
Basic .NET for SQL Server 2 00 0
This book aims to give professional developers the background that they need to
program SQL Server applications with Microsoft Visual Basic .NET. This overall
goal implies three guidelines:
• First, the book targets practicing developers. I n my experience, these are
busy professionals who need the details fast. These individuals already
know how to build applications. They buy a book to learn how to build
those applications with a specific set of tools.
• Second, the book is about building applications for SQL Server 2000. This
focus justifies in-depth coverage of SQL Server program m ing topics— in
particular, T-SQL, Microsoft’s extension of the Structured Query Language
(SQL).
• Third, the book illustrates how to program in Visual Basic .NET, but with
particular emphasis on database issues for SQL Server 2000. Special
attention goes to related .NET technologies, such as the .NET Fram ework,
ADO.NET, ASP.NET, and XML Web services.
My goal in this chapter is to equip you conceptually for the rest of the book.
Therefore, this chapter includes material that acquaints you with application
developm ent techniques and topics for SQL Server 2000 and Visual Basic .NET.
The discussion of the samples in this chapter generally aim s to convey broad
approaches instead of how to run the sample. All the remaining chapters except
for Chapter 8, another conceptual chapter, have sam ples with instructions aim ed
at professional developers.
I believe that the overwhelm ing majority of professional Visual Basic developers
have no hands-on fam iliarity with Visual Basic .NET and its related technologies.
If you already knew Visual Basic .NET, it wouldn’t make any sense to buy a book
describing how to use it. This chapter therefore focuses on how to get started
with Visual Basic .NET and one of its core related technologies for those building
SQL Server applications— ADO.NET. I also believe that m ost Visual Basic
developers don’t have an intimate knowledge of SQL Server— especially for
creating user-defined objects, such as tables, views, and stored procedures. This
capability can em power you to build m ore powerful and more secure applications.
As you learn about database objects and how to create them in Chapter 2
through Chapter 7, reflect back on the Visual Basic .NET coverage in this chapter
and how to marry database creation techniques and Visual Basic .NET
developm ent techniques. One of the best tools to build database objects is SQL
Server 2000 Query Analyzer. This chapter’s closing section conveys the basics of
Query Analyzer that you need to follow the sam ples in Chapter 2 through Chapter
7.
Visual Studio .NET, the Visual Basic .NET I DE
Visual Studio .NET is the new m ultilanguage integrated developm ent environm ent
(I DE) for Visual Basic, C# , C+ + , and JScript developers. I f you are developing
solutions for Visual Basic .NET, I definitely recom mend that you use Visual Studio
.NET as your developm ent environm ent. This section dem onstrates how to get
started using Visual Studio .NET for developing solutions with Visual Basic .NET.
Visual Basic .NET is available as part of Visual Studio .NET in four editions:
• Professional
• Enterprise Developer
• Enterprise Architect
• Academ ic
All four editions of Visual Studio .NET include Visual Basic .NET, Microsoft Visual
C# .NET, Microsoft Visual C+ + .NET, and support for other languages. I n
addition, Microsoft offers Visual Basic .NET Standard, which doesn’t include Visual
C# .NET or Visual C+ + .NET.
Because this book targets professional Visual Basic developers creating SQL
Server applications, it uses the Enterprise Developer Edition of Visual Studio
.NET. You may notice some differences if you’re using another edition.
Visual Studio .NET can be installed on computers running one of five operating
system s: Windows 2000, Windows NT, Windows XP, Windows ME, and Windows
98. Not all the .NET Framework features are available for each operating system.
For example, Windows 98, Windows Me, and Windows NT don’t support
developing ASP.NET Web applications or XML Web services applications. The
samples for this book are tested on a computer running Windows 2000 Server,
which does support all .NET Fram ework features.
Starting Visual Studio .NET
To open Visual Studio .NET, click the Start button on the Windows taskbar,
choose Programs, and then choose Microsoft Visual Studio .NET. Visual Studio
displays its integrated developm ent environm ent, including the Start Page (unless
you previously configured Visual Studio to open differently). From the Start Page,
you can configure Visual Studio to work according to your developm ent
preferences, and you can start new solutions as well as open existing projects.
Configuring Visual Studio .NET for Visual Basic .NET
Use the links on the left side of the Start Page to begin configuring Visual Studio
.NET for developing solutions in Visual Basic .NET. Click the My Profile link to
open a pane in which you can specify an overall profile as well as individually
indicate your preferences for Keyboard Schem e, Window Layout, and Help Filter.
You also can designate the initial page that Visual Basic .NET displays. When you
are beginning, it m ay be particularly convenient to choose Show Start Page. As a
Visual Basic developer who has worked with Visual Basic 6, you m ight feel m ost
familiar with a layout that reflects your prior developm ent environm ent. Figure 1-
1 shows these My Profile selections.
Figure 1 -1 . My Profile selections for starting Visual Studio .NET for a
Visual Basic developer.
Using the Start Page
After setting your profile, you can return to the initial Start Page pane by
choosing the Get Started link from the menu on the left border. I f you had
created previous solutions, the last four m odified projects would appear on the
Projects tab of the Start Page. The tab shows project nam es along with date last
modified. I f a project you want to view doesn’t appear on the list, you can click
the Open Project link to display the Open Project dialog box and then navigate to
a directory containing the previously created solution. Select the project’s folder
that you want to open in the I DE, and double-click the solution file (.sln) for the
project. The next section illustrates this process in the context of a sample
project.
To create a new solution, click the New Project link to open the New Project
dialog box. I f you saved preferences such as those shown in Figure 1-1, the
dialog will automatically select Visual Basic Projects in the Project Types pane of
the New Project dialog box. On the right, you can select a template for launching
a project. Table 1-1 shows the project template nam es along with a brief
description available from the Enterprise Developer Edition of Visual Studio .NET.
Choosing a template (by clicking OK after selecting a template) opens a project
ready for creating the type of solution that you want to develop. When Visual
Studio .NET saves the tem plate to start a new project, it specifies either a file
folder or a Web site for the template’s files; you can override the default nam es
for the file folder and Web site.
Note
Not all the project template types in Table 1-1 are available
with the non-Enterprise (or Standard) editions of Visual
Studio .NET. In addition to the empty projects, the Standard
editions make available the Windows Application, ASP.NET
Web Application, ASP.NET Web Service, and Console
Application templates.
7DEOH9LVXDO%DVLF1(73URMHFW7HPSODWH7SHV
7HPSODWH1DPH UHDWHV$
Windows
Application
Windows application with a form
Class Library Windows application suitable for a library of classes without a
form
Windows Control
Library
Project for developing custom reusable form controls for
Windows applications
ASP.NET Web
Application
Web application on a Web server
ASP.NET Web
Service
XML Web service on a Web server
Web Control Library Project for developing custom reusable controls for Web
applications
Console Application Command line application that operates in an MS-DOS–style
window (the Console)
Windows Service Windows service, form erly NT service, application that runs
in the background without its own custom user interface
Em pty Project Local project with no custom style
Em pty Web Project Web project with no custom style
New Project I n
Existing Folder
Blank project in an existing folder
There are two main categories of templates: Web projects and local projects. Web
projects perm it a browser to serve as the client for a project. Web projects are
optim ized for form processing on the Web server. Local projects offer custom
form user interfaces with the capability of processing on a local workstation. Local
projects can provide richer environments more conducive to client-side
programm ing, but local projects don’t offer the wide accessibility of solutions
running from a Web server.
Creating and Running a Console Application
When you select a Console Application template and click OK to launch a new
project, Visual Studio .NET responds by opening a project with a blank module. I n
addition to the Module window, Visual Studio displays Solution Explorer and the
Properties window. You can enter code directly into the Module window, which
appears as a tab that you can select alternately with the Start Page. Figure 1-2
shows a code sam ple in the Main subroutine that prompts for a first and second
nam e before com bining them and displaying them in the Console (the computer’s
monitor). The code is also available as MyNam eIsFrom Console in the Chapter 1
folder on the companion CD for this book. Although Visual Basic developers didn’t
previously have Console applications routinely available, this sample should be
very easy to follow. The final two lines present an instruction and cause the
window to remain open until the user responds to the instruction. This allows the
user to view the full name in the Console window.
Figure 1-2. A Console application for displaying a full nam e based on user
input for first and second nam es.
To the right of the Module window are two other windows. The top one of these is
Solution Explorer. I t shows the file structure for the solution. Solution Explorer
indicates in its first line that the solution consists of just one project. Below that
line appears the name of the project, MyNam eI sFrom Console. Within the project
are three entries: one each for the References, AssemblyI nfo.vb, and Module1.vb
elem ents within the solution’s project. By default, the Properties window is below
Solution Explorer. I n the Full Path property text box is an excerpt showing the
path to Module1.vb on my computer. When you click the project name in Solution
Explorer, the Project Folder text box in the Properties window displays the path of
the directory holding the solution’s files. It is this directory that you copy to
deploy your solution on another computer with the .NET Fram ework installed. The
solution won’t run without the com mon language runtime on the computer to
which you copy the directory containing the .NET Fram ework solution. See
Chapter 8 for m ore detailed coverage of the .NET Fram ework, including the
runtime and distributing .NET Fram ework solutions as assemblies of files in
folders.
You can test run the application by choosing Start from the Debug m enu, or by
pressing F5. This opens the Console window with a prompt to enter a first nam e.
After you close your application and save any changes to it, your solution appears
on the Start Page for recent solutions. I f you start Visual Studio .NET and the
solution you want to open doesn’t appear on the Projects tab of the Start Page,
you can also open the solution by clicking Open Project. I n the Open Project
dialog box, choose the file with the .sln extension and the solution’s nam e
(MyNam eIsFromConsole). A solution can contain just one .sln file, but it can
contain m ultiple projects.
You also can run the solution and open the Console window directly from
Windows Explorer without using Visual Studio .NET. Open the bin subdirectory
within the directory containing the assembly folder for the solution. Then double-
click the MyNameIsFrom Console.exe file. This opens the Console window with the
prompt for a first nam e.
An Overview of ADO.NET Capabilities
ADO.NET encapsulates the data access and data manipulation for the .NET
Framework. This section gives you an overview of the topic that equips you for a
starter sam ple in the next section. Microsoft chose the nam e ADO.NET for the
.NET Framework data access com ponent to indicate its association with the earlier
ADO technology for data access. While there are som e sim ilarities in syntax
between ADO.NET and ADO (particularly for connection strings), many will find
the differences are m ore obvious than the sim ilarities. These differences
substantially upgrade ADO.NET over ADO in two key areas— scalability and XML
(Extensible Markup Language) interoperability. As a result, you will be able to
create database applications with ADO.NET that serve m ore users and share m ore
data than you did with ADO. See Chapter 10 for a m ore intensive examination of
ADO.NET. Chapter 12 explicitly explores interoperability between ADO.NET and
XML.
.NET Data Provider Types
Your .NET Fram ework solutions require .NET data providers to connect to data
sources. These providers are different from those used with ADO, but there are
distinct similarities in some of the ways you use them. With .NET data providers,
your solutions can connect, read, and execute commands against data sources.
The .NET providers also offer selected other functions, such as the m anagement
of input and output parameters, security, transactions, and database server
errors.
Visual Studio .NET ships with two .NET data providers— the SQL Server .NET data
provider and the OLE DB .NET data provider. In addition, you can download an
ODBC .NET data provider from the Microsoft MSDN download site
(http: / / msdn.m icrosoft.com/ downloads/ default.asp).
Note
As I write this chapter, the ODBC .NET data provider just became
available with the rollout of the shipping version of Visual Studio
.NET. You can download it from
http: / / msdn.microsoft.com/ downloads/ default.asp?url= / downloads/ s
ample.asp?url= / msdn-files/ 027/ 001/ 668/ msdncompositedoc.xml.
The URLs for resources sometimes change. You can always search
for the ODBC .NET data provider at the MSDN download site to
obtain its current download location.
The three providers taken together offer fast, highly focused access to selected
data sources as well as general access to a wide range of possible data sources.
The SQL Server .NET data provider is optim ized for SQL Server 7.0 and SQL
Server 2000. This data provider connects directly to a SQL Server instance.
The OLE DB .NET data provider connects to OLE DB data sources through two
intermediate layers— the OLE DB Service Component and the classic OLE DB
provider introduced along with ADO. The OLE DB Service Component m anages
connection pooling and transaction services. The classic OLE DB provider, in turn,
directly connects to a database server. Microsoft explicitly tested the OLE DB .NET
data provider with SQL Server, Oracle, and Jet 4.0 databases. Use the OLE DB
.NET data provider to connect to the SQL Server 6.5 version and earlier ones.
This provider is also good for connecting to your Microsoft Access solutions based
on the Jet 4.0 engine.
The OLE DB .NET data provider definitely doesn’t work with the OLE DB provider
for ODBC data sources (MSDASQL). Because the .NET OLE DB data provider
doesn’t connect to ODBC data sources, you require the ODBC .NET data provider
for connecting to ODBC data sources from your .NET Framework solutions.
There are four main .NET data provider classes for interacting with a rem ote data
source. The nam es of these classes change slightly for each type of provider, but
each .NET data provider has the sam e four kinds of classes. The names for the
SQL Server .NET data provider classes for interacting with SQL Server instances
are SqlConnection, SqlCommand, SqlDataReader, and SqlDataAdapter. You can
use the SqlDataReader class for read-only applications from a SQL Server data
source. Two especially convenient ways to display results with a SqlDataReader
class are in a m essage box or the Visual Studio .NET Output window. The
SqlDataAdapter class acts as a bridge between a remote SQL Server data source
and a DataSet class instance inside a Visual Basic .NET solution.
A data set in a Visual Studio solution is a fifth type of ADO.NET class. A data set
can contain m ultiple tables. A sixth ADO.NET class is the DataView class, which
acts like a view based on a table within a DataSet object. Windows Forms in
Visual Basic .NET applications can bind only to tables within a DataSet object and
DataView objects. I examine the DataSet object later in this section. Chapter 10
includes a systematic summary of all six ADO.NET classes that reviews selected
properties and m ethods of each class. The overview of ADO.NET classes in
Chapter 10 is supported by num erous code samples that illustrate how to
manipulate instances of the classes programmatically.
Note
In order to use abbreviated names, such as those listed in
this section for the SQL Server .NET data provider class
instances, your application needs a reference to the SqlClient
namespace. You can create such a reference with an Imports
System.Data.SqlClient statement just before a Module
declaration.
SqlConnection Class
An instance of the SqlConnection class can interface directly with a SQL Server
data source. Use a constructor statement to instantiate a SqlConnection object
from the SqlConnection class. The constructor statement is a new type of sy-ntax
for .NET Fram ework solutions. This type of statement perm its you to declare,
instantiate, and pass startup param eters to an object based on a class. With the
SqlConnection constructor statem ent, you can specify a connection string as an
argum ent for the constructor statem ent. Alternatively, you can assign the
connection string to the SqlConnection object after its instantiation with a
property assignm ent statement for the ConnectionString property. The following
line shows the syntax to instantiate a new SqlConnection object, MySQLCnn1,
with a connection string designating integrated security to the m ydb database on
the myserver instance of SQL Server. You don’t have to explicitly indicate a
provider because the constructor statem ent reveals the type of provider through
its reference to the SqlConnection class.
Dim MySQLCnn1 As New _
SqlConnection(“Integrated Security=SSPI;  _
Data Source=myserver;Initial Catalog=mydb)
After instantiating a SqlConnection object, you need to invoke its Open method
before the object can link another object based on one of the other SQL Server
.NET data provider classes, such as SqlCommand, SqlDataAdapter, or
SqlDataReader, to a SQL Server instance. I nvoke the Close m ethod to recover the
resources for a SqlConnection object when your solution no longer needs it. The
Close m ethod rolls back any pending transactions and releases the connection to
the connection pool. The Dispose m ethod is also available for removing
connections, but it invokes the Close m ethod and performs other .NET
adm inistrative functions. Microsoft recomm ends the Close m ethod for removing a
connection. Unclosed connections aren’t returned to the connection pool.
SqlCom m and and SqlDataReader Classes
One way to put a connection to use is to employ it along with the SqlCom mand
and SqlDataReader objects. A SqlDataReader object can maintain an open
forward-only, read-only connection with a SQL Server database. While the
SqlDataReader using a SqlConnection object is open, you cannot use the
SqlConnection object for any other purpose except to close the connection.
Closing a SqlDataReader object releases its associated SqlConnection object for
other uses. The SqlDataReader class doesn’t have a constructor statement. You
declare the SqlDataReader object with a Dim statement and assign a result set
from a SqlCommand object to a SqlDataReader with the ExecuteReader method
of the SqlCommand object. Finally, invoke the SqlDataReader object Read
method to open a row from the result set in the SqlDataReader.
The SqlCommand object can serve multiple functions, including processing a T-
SQL statem ent against a connection. When used in this fashion, the SqlCommand
can take two argum ents. The first can be a T-SQL data access statement, such as
SELECT * FROM MyTable . The second SqlCom m and argum ent designates the
source connection for the T-SQL statem ent. For example, you can use the name
of a SqlConnection object, such as MySQLCnn1.
Figure 1-3 shows the route from a SQL Server data source to a SqlDataReader
object. Although the SqlConnection and SqlCom mand objects support two-way
interaction with a data source, the SqlDataReader object allows read-only access
to the result set from the T-SQL statem ent serving as an argum ent for a
SqlCommand constructor. Because a SqlDataReader object cannot specify its own
data source, a SqlDataReader object must link to a SqlConnection object through
an intermediate SqlCom mand object.
Figure 1 -3 . A schem atic illustrating the route by w hich a SqlDataReader
object returns values to an application.
The SqlCommand object can do more than provide a result set to the
SqlDataReader object. The discussion of the SqlDataReader object described the
use of the SqlCom mand object ExecuteReader method. Three related methods
highlight som e contrasting SqlCom mand object functionality.
• Invoke the ExecuteNonQuery m ethod to perform two types of actions.
First, use this method to perform data definition tasks, such as creating
stored procedures and views. Second, the ExecuteNonQuery m ethod can
enable data m anipulation tasks, such as inserts, updates, and deletes.
• Next, you can apply the ExecuteScalar m ethod to a SqlCommand object
when you want to return a single value from a SELECT statement. The
method returns the first colum n from the first row of a result set. I f you
program this cell to be an aggregate value such as a count or sum , you
can readily extract that single value with the ExecuteScalar method.
• Finally, the ExecuteXMLReader m ethod opens a T-SQL source statem ent
with a FOR XML clause into an XMLReader object. Chapter 6 contains
extensive coverage of the FOR XML clause. Objects for dealing with XML
will be covered in Chapter 12.
The SqlDataAdapter Class and the DataSet Class
You use objects based on the SqlDataAdapter class in combination with objects
based on the DataSet class. A DataSet object, which is an instance of the DataSet
class, represents an in-memory cache of data retrieved from a database. The
DataSet object offers a disconnected data source as opposed to the always-
connected data source for SqlDataReader objects. As a consequence, using the
SqlDataAdapter and DataSet objects instead of a SqlDataReader object improves
application scalability. This scalability improvem ent results because the DataSet
doesn’t persist a connection to its underlying data source over the whole of its
lifetim e as does the SqlDataReader object. While the SqlDataReader isn’t as
scalable as the SqlDataAdapter/ DataSet combination, the SqlDataReader can
provide faster performance from a remote data source because it delivers data in
the style of a forward-only, read-only cursor— the classic firehose delivery m odel.
Note
The term firehose refers to the fact that data gushes out of a
forward-only, read-only cursor.
The SqlDataAdapter and DataSet objects combine to enable both data access and
data manipulation capabilities. This is important because SqlDataReader objects
provide strictly data access capabilities (that is, you cannot perform update,
insert, or delete tasks with a SqlDataReader object). Use the SqlDataAdapter Fill
method to populate a DataSet object with values from a SQL Server data source.
Because a single DataSet object can work with multiple SqlDataAdapter and OLE
DB DataAdapter objects, you can populate a single DataSet object with
heterogeneous data sources from m ultiple database servers. For exam ple, you
can populate a single data set with tables, views, or stored procedures from two
different SQL Server instances or from Access and Oracle data sources in addition
to a SQL Server data source. Furtherm ore, you can join all the data sources
within a DataSet object on fields with comm on data types.
Use the SqlDataAdapter Update m ethod to transfer changes from a DataSet
object to its underlying data sources. When users perform insert, update, and
delete operations against the contents of a DataSet object, those m odifications
don’t transfer to the data sources for the DataSet object until your application
invokes the Update m ethod for a SqlDataAdapter object underlying the data
source. Despite its nam e, the Update method can process all three types of data
manipulation operations. However, you need a custom SqlCommand object to
accomm odate each type of data manipulation task. Therefore, a SqlDataAdapter
can relate to a remote data source through m ore than a single SqlCom mand
object. Between the tim e you populate the DataSet object and the tim e your
application invokes the SqlDataAdapter Update method, it’s possible for the
underlying data source on a SQL Server instance to change. Any changes can
cause exceptions because the original values in a data set can be different from
the current values in the SQL Server data source. The SqlDataAdapter has events
and properties to help manage exceptions that can occur during an update
process. Figure 1-4 presents a schematic diagram summarizing how
SqlDataAdapter and DataSet objects exchange data with an underlying data
source. By contrasting this diagram with the one in Figure 1-3, you can easily
spot an important difference between the SqlDataReader and a DataSet object
supplied by a SqlDataAdapter object. The capability of perform ing data
manipulation with the DataSet object is a critical feature that m eans many
applications will rely on a DataSet object instead of a SqlDataReader object.
Figure 1-4. A schem atic illustrating the route by w hich SqlDataAdapter
and DataSet objects exchange values w ith a SQL Server data source.
The DataSet object offers an object model for m anaging the individual elements
within it. The DataSet object consists of a DataTable collection (along with other
elem ents). This collection can contain one or more tables. You can create these
tables with the SqlDataAdapter Fill m ethod when you initially populate a DataSet
object from a SQL Server data source. The SelectCommand property, which is a
T-SQL statem ent or a stored procedure, for a SqlDataAdapter object can serve as
the basis of a table in the DataTable collection for a DataSet object. You can use
multiple SqlDataAdapter objects to add m ore than one table to a DataSet object.
Each table has a rich object model that perm its the designation of prim ary keys
and foreign keys as well as constraints to manage data integrity within a table.
One very practical use for the DataTable collection and the object m odel for
individual tables is that you will use it to navigate among the values within a
DataSet object.
Note
In addition to referencing the column values of rows within
an individual DataTable in a DataSet object, you can
reference the schema of DataTable objects within a DataSet
object. This is particularly convenient when you want to
create a table that you want to populate with data from an
XML document.
The DataSet object supports four key m ethods for exchanging its data with XML
documents. Two of the methods are used for writing XML docum ents based on a
DataSet object, and two are for reading XML docum ents into a DataSet object.
Within each pair, one m ethod focuses just on transferring schema information
and the other focuses on transferring data as well as schema information.
A Starter ADO.NET Sam ple
This section presents a starter sample to illustrate som e of the concepts
described in the preceding section. Don’t worry about following the details of the
example. I nstead, pay attention to how easy it is to get started with ADO.NET.
This section reinforces the presentation of basic ADO.NET concepts described in
the preceding section with simple drag-and-drop techniques and a little code
included to tie objects together or enable selected functionality. See Chapter 10
for a collection of code samples that illustrate how to program ADO.NET objects
when you require custom ized solutions not readily available from the graphical
developm ent environm ent. Most professional developers get called on to do the
hard work that goes beyond dragging and dropping objects. After all, if it were
easy, they wouldn’t need you. However, it is nice to start out by seeing how easy
it is to create a simple solution mostly by dragging and dropping.
Note
For those who want the sample from this section as a point
of departure, it is available on the book’s CD as the
GraphicalDataBind solution.
Adding a SqlDataAdapter, SqlConnection, and DataSet
You can drag a SqlDataAdapter object to a form just like a text box or a com bo
box in Visual Basic 6. There is even a wizard to help you configure the
SqlDataAdapter object. Figure 1-5 shows the opening screen imm ediately after
dragging a SqlDataAdapter object to the startup blank form, Form 1, for a
Windows application. You can use this wizard to specify two ADO.NET objects.
Figure 1 -5 . The Data Adapter Configuration W izard enables you to
graphically configure a SqlDataAdapter object and its related
SqlConnection object for use w ith a W indow s form .
First, you can designate a SQL Server database to which to connect; this creates
a SqlConnection object. This wizard offers several routes for specifying a
database connection. For example, you can pick a previously created connection,
or you can create a new collection from the Data Link Properties dialog box. This
dialog box lets you specify the comm on connection string argum ents, such as a
database server, a type of authentication, and a database nam e. I n this starter
sample, I used the default connection to the Northwind database.
Second, you can specify a data source within a database connection using a SQL
string or a stored procedure. For this starter application, I used SELECT
CategoryID, CategoryName FROM Categories as the SQL string source for the
SqlDataAdapter object. Although a graphical designer is available for building
query statem ents, you will be severely hampered as a SQL Server developer if
you don’t learn T-SQL, the dialect of SQL that SQL Server supports. I n addition,
you will find a grasp of T-SQL important for crafting the statem ents for the
SqlCommand objects that enable you to build solutions that update a SQL Server
data source from a Windows application.
After you finish configuring the Data Adapter Configuration Wizard, the
component tray will open below your blank form. The tray will hold the two
objects that the wizard created— a SqlDataAdapter object and a SqlConnection
object. Because a SqlDataAdapter object is m erely a bridge between a remote
data source and a data set in a Windows application, you will need to create a
data set. Then your SqlDataAdapter object can fill the data set with data from the
rem ote data source specified by your replies to the Data Adapter Configuration
Wizard.
Im mediately after a SqlDataAdapter object is created, three links are displayed
near the bottom of the Properties window for the object. One of these links reads
Generate Dataset. Clicking the link opens the Generate Dataset dialog box, in
which you designate an existing data set or specify the name for a new one.
Figure 1-6 shows the specification of a new data set nam ed DsCategories for the
SqlDataAdapter created with the Data Adapter Configuration Wizard. When you
click OK within the Generate Dataset dialog box portrayed in Figure 1-6, Visual
Basic .NET adds a new object nam ed DsCategories1 to the tray below the form .
In addition, Visual Basic .NET adds an XML schema nam ed DsCategories.xsd to
the solution that describes the data set. You can view the schema for the data set
graphically or as XML code by double-clicking the file’s name in Solution Explorer.
The schema’s graphical view is interactive so that you can change the data type
specification for columns and make other design changes to the Categories table.
The Properties window for the DsCategories.xsd shows the nam e of the table
specification as Categories. At this point, you have completed the creation of the
DsCategories data set, which contains a DataTable named Categories.
Figure 1-6 . You need to add a data set before you can use a
SqlDataAdapter. You can add the data set as sim ply as giving it a nam e in
the Generate Dataset dialog box.
Note
Although the Generate Dataset dialog box shows the data set
name as DsCategories, Visual Basic .NET assigns
DsCategories1 as the data set name in the tray below Form1.
After adding a SqlDataAdapter object and a DataSet object to an application, you
can preview the data that the SqlDataAdapter will bring to the application.
Clicking the Preview Data link in the Properties window for a SqlDataAdapter
object opens the Data Adapter Preview dialog box. Click the Fill DataSet button to
display the data in the dialog box. Because of the SQL statem ent used when
configuring our SqlDataAdapter object, the button populates the form with a table
that shows the CategoryID and CategoryName column values from the Northwind
database. Don’t confuse clicking the button on the form with populating the data
set for use with a Windows form . Filling the Categories data table in the
DsCategories data set with data values from a SQL Server instance and displaying
the values on a Windows form requires two m ore steps. First you need to invoke
the Fill m ethod for the SqlDataAdapter object. Second you need to bind form
controls, such as text boxes, to colum ns in the local Categories data table.
Filling a Data Set and Binding Controls to I t
A logical place to fill a data set for use with a form is the form Load event
procedure. A single line of code in the tem plate will fill the data set. Run the line
of code from the form Load event to make the contents for the data set available
as soon as the form opens. The following code segment illustrates the syntax for
invoking the SqlDataAdapter Fill m ethod to populate a data set. The event
procedure is for Form1, which is the default startup object for a Windows
application. The Fill method takes two argum ents in this situation. First you
specify the data set name. Second you designate the DataTable nam e within the
data set. You must nam e a DataTable object because one data set can hold
multiple DataTable objects. Leaving out the DataTable nam e will cause an error.
Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
SqlDataAdapter1.Fill(DsCategories1, “Categories”)
End Sub
After you fill the data set, you can bind it to controls on a form. For example, I
added two text boxes to Form1 for the starter ADO.NET application. You can do
this with the Toolbox just as in prior Visual Basic versions. What’s new is that
there is now a DataBindings property. You can graphically bind the Text property
for a text box control to a colum n in the Categories data table. Figure 1-7 shows
how to bind the Text property for TextBox1 to the CategoryID colum n in the
Categories data table. The Form1.vb Design tab shows TextBox1 selected on
Form1. The Properties window reveals the assignment of the CategoryID colum n
to TextBox1. Selecting a colum n from the Categories data table completes the
task. I followed the sam e process for TextBox2, but I selected CategoryName
instead.
If you run Form1 by pressing the F5 key, you see the form with two text boxes
showing the CategoryID and CategoryName colum n values for the first row from
the Categories data table. While it is nice to see data in the text boxes,
applications typically seek to allow users to at least browse through data. To
enable browsing, you need controls that let a user navigate through the rows of
the Categories data table.
Figure 1-7. Use the DataBindings property to bind the Text property of a
text box control to a colum n in a DataTable object.
Navigating Through Row s
A row of button controls can provide the basis for a navigation bar. All we need
are Text property settings indicating the navigation each button provides and
event procedures for the Click event of each button that navigates through the
rows in the Categories data table. I added four button controls to Form 1 with
event procedures to control navigation in response to click events. For example,
Figure 1-8 shows the text boxes after the button control on the far right has been
clicked. Notice that the last row (for CategoryID 8 in the Categories data table)
shows in the top text box.
Figure 1-8. Form 1 in the starter ADO.NET sam ple after the last- row
button (  | ) has been clicked displays colum n values from the
corresponding row in its text box controls.
The following set of Click event procedures for Button1 through Button4 shows
how easy it is to control navigation. The buttons from left to right navigate to the
first row, the previous row, the next row, and the last row. The procedures
update the Position property of the BindingContext property on the form for the
Categories DataTable in the DsCategories1 data set. This manipulation, in turn,
affects all text box controls bound to the Categories data table. Chapter 10 drills
down m ore deeply into the object m odel supporting these manipulations. The
important point to notice here is that the code doesn’t have to handle moving
past the beginning or ending row because ADO.NET is smart about recognizing
either end of a rowset, such as the Categories data table.
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click
’Move to the first row.
Me.BindingContext(DsCategories1, “Categories”).Position _
= Me.BindingContext(DsCategories1, “Categories”). _
Position.MinValue
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button2.Click
’Move to the previous row.
Me.BindingContext(DsCategories1, “Categories”).Position _
-= 1
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button3.Click
’Move to the next row.
Me.BindingContext(DsCategories1, “Categories”).Position _
+= 1
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button4.Click
’Move to the last row.
Me.BindingContext(DsCategories1, “Categories”).Position _
= Me.BindingContext(DsCategories1, “Categories”). _
Position.MaxValue
End Sub
Using Query Analyzer
Query Analyzer is your friend for debugging T-SQL statem ents. Because T-SQL is
so important to SQL Server development, mastering this tool can be part of what
makes you into a great SQL Server developer.
W hat’s Query Analyzer For?
Query Analyzer is one of the client tools that ships with SQL Server 2000. This is
another way of saying that Query Analyzer isn’t part of the database server. You
are authorized to use Query Analyzer, and the other client tools, by the allocation
of a Client Access License to your workstation. Although the client tools don’t ship
with MSDE 2000 (Microsoft SQL Server 2000 Desktop Engine), they are available
with any regular version of SQL Server 2000, such as the Enterprise, Standard,
Developer, and Personal editions.
I think of Query Analyzer as sort of an I DE for running T-SQL statements. This
client tool is a real help for anyone programm ing solutions for SQL Server. Query
Analyzer will help you to easily and quickly debug your T-SQL code. Although you
can program and debug T-SQL directly with Visual Basic .NET and ADO.NET,
Query Analyzer provides a m uch richer environment that makes your T-SQL
coding go m uch faster. Even if an application calls for running T-SQL inside of a
Visual Basic .NET application, I often find it convenient to debug the statem ent in
Query Analyzer before inserting the T-SQL code into my Visual Basic .NET
application.
There are at least five reasons to become comfortable with T-SQL, and using
Query Analyzer m ay be one of the best ways to do that.
• You can build richer query statem ents that return precisely the data you
want without having to resort to a graphical query builder. I ndeed, some
query operations, such as those perform ed by the UNI ON function, cannot
be represented by graphical query designers.
• You can create data manipulation statements for updating, inserting, and
deleting rows. Graphical query builders aren’t always effective at creating
these statements.
• You can program security topics, such as creating SQL Server logins and
controlling access to database objects and server adm inistration functions.
• You can program the creation of databases and the objects within them ,
such as tables, stored procedures, and user-defined functions. Several
chapters within this book include scripts to create databases and populate
those databases with objects automatically.
• You can take advantage of programm ing features, such as IF…ELSE
statements, local variables, param eters, and return values to build
flexibility and user interactivity into your applications.
Many T-SQL samples are especially designed for use with Query Analyzer. For
example, these samples set the database context for T-SQL code with a USE
statement. This statement explicitly targets Query Analyzer and doesn’t run from
most other SQL Server clients, such as Visual Basic .NET. Books Online, the SQL
Server Help system, follows this convention with its samples. Therefore, a basic
familiarity with Query Analyzer will help you to take advantage of the rich
collection of samples in Books Online. I n addition, the T-SQL samples in this book
follow the same convention. Therefore, this section gives you a brief introduction
to Query Analyzer. You will have ample opportunity to reinforce and extend the
understanding this section conveys with the T-SQL samples throughout the
balance of this book. I n fact, the comm entary for these samples som etimes
describes how to run code in Query Analyzer.
Making a Connection w ith Query Analyzer
To start Query Analyzer, click the Start button on the Windows taskbar; choose
Programs, then Microsoft SQL Server, and then Query Analyzer. When you start
Query Analyzer this way, you will be greeted with the Connect To SQL Server
dialog box. Recall that Query Analyzer is a client tool. Therefore, you can use it
with any SQL Server instance that you can connect to and for which you have
access perm ission. If you are connecting to the local instance of SQL Server on
your computer for which you are the adm inistrator, you can designate the SQL
Server as “(local)” and choose Windows Authentication. (See Figure 1-9.) The
settings in Figure 1-9 are suitable for connecting to SQL Server with any Windows
login. Click OK to complete the connection to the server.
Figure 1 -9. The connection settings for logging in to the local instance of
SQL Server w ith W indow s authentication.
Query Analyzer offers the normal flexibility in how you connect to a SQL Server
instance. As I already noted, you can connect with any Windows login that a SQL
Server instance recognizes. I n addition, you can use SQL Server authentication. I f
you select SQL Server Authentication rather than Windows Authentication in the
Connect To SQL Server dialog box, Query Analyzer enables the Login Name and
Password text boxes so that you can specify a SQL Server login and password. I n
addition, you can connect to any other SQL Server instance besides the local
default one. I f you know the nam e of the instance to which you want to connect,
type the nam e in the SQL Server combo box in the Connect To SQL Server dialog
box. Otherwise, click the browse button (…) next to the combo box. This opens a
dialog box that lists SQL Server instances currently active on the network to
which your workstation connects. Select an instance nam e to specify a connection
to that server.
See Chapter 7 for more about SQL Server security and logging in to SQL Server
instances with different types of logins. Until Chapter 7, one safe approach to
running the samples is to connect as a m ember of the sysadmin server role, such
as the SQL Server administrator. Members of the sysadm in server role have
unrestricted perm ission on a SQL Server instance. Chapter 7 gives guidelines and
procedures for restricting the perm issions for an application’s users.
Running, Saving, and Opening T- SQL Scripts
When Query Analyzer opens as described in the preceding section, it will connect
a user to the default database for the login that the user specified in the Connect
To SQL Server dialog box. The default is the master database unless a database
adm inistrator changed the standard default database specification when adding a
new login.
Because m ost user-defined queries don’t interrogate the m aster database, which
is a system database, you will usually want to change the database context
before writing any SQL query statem ents. You can employ the USE statement for
this. Just follow USE with the nam e of the database for which you want to write a
query. The following statement directs Query Analyzer to run query statements
against the pubs database (until another USE statement or some other specific
instruction to use another database). The pubs database is one of the sample
databases that is installed automatically with SQL Server 2000.
USE pubs
Figure 1-10 shows this sim ple SELECT statement for the authors table in the pubs
database:
SELECT au_fname, au_lname, state
FROM authors
WHERE contract = 1
The SELECT statement appears after the USE statement in the Editor pane, which
is where you type T-SQL statements in Query Analyzer. The statement selects
three colum n values from the authors table if a row has a contract column value
equal to 1. You can see the result set from the query statem ent in the Results
pane that appears below the Editor pane, as shown in Figure 1-10. Query
Analyzer automatically displays the Results pane when you run a query, but you
can also show and hide it by pressing Ctrl+ R.
By default, Query Analyzer displays the result set in the Results pane within a
spreadsheetlike grid. At the bottom of the Results pane are a Grids tab and a
Messages tab. You can click the Messages tab to see general feedback from SQL
Server about how a query statem ent operated. For exam ple, the Messages tab for
the query in Figure 1-10 says, “(19 row(s) affected)”, which corresponds to the
number of rows the query statem ent returns. Warnings and error feedback from a
SQL Server instance appear in the Messages pane.
You also can choose to display the result set in the Results pane as text in
colum ns. I n that case, there is only a Results tab at the bottom of the Results
pane, and both the result set and m essages are displayed in the pane. To specify
whether you want to set the result set in a grid or in text, choose Options from
the Tools menu, then choose the Results tab, and then use the combo box at the
right of the Options dialog box to specify Results To Text, Results To Grids, or
Results To File.
Figure 1 -1 0. A query statem ent for the pubs database and its result set
run from Query Analyzer.
After creating a T-SQL script, you can save it so that you or others can reopen it
and use it again later. Most of the sample files for Chapter 2 through Chapter 7
are saved scripts with the .sql extension. To save a script file for the first time or
resave an existing script file with a new nam e, choose Save As from the File
menu, navigate to a desired folder with the Save Query dialog box, enter a
filename, and click Save. These steps will save the current script in the
designated folder with the filenam e that you specify with the .sql extension. For
example, I followed these steps to save the script shown in Figure 1-10 to my
computer. I saved the file as AuthorsQuery.sql in the Chapter01 folder of the SQL
Server Developm ent With VBDotNet directory on my C drive.
There are several ways to open a script file. For exam ple, imm ediately after
connecting to a SQL Server instance for a new Query Analyzer session, you can
choose Open from the File menu, navigate in the Open Query File dialog box to
the folder with the script file (.sql), highlight the filenam e, and click Open. These
steps open an Editor pane in Query Analyzer with the saved script file. Figure 1-
11 shows the opened script file saved in the preceding paragraph in an Editor
pane. Notice that the title bar for the pane includes the path along with the
filename and extension.
The Object Browser will also script objects for you. To automatically create a
script for an object, right-click an object such as the Categories table, and choose
Script Object To New Window As and then the Create command. This feature
allows you to see the T-SQL script behind your favorite objects to learn how to
make m ore objects like them or to help you change their design to m eet
expanded objectives.
As you build up your collection of databases and the objects within them , you
might start to find special value in the Object Search component within Query
Analyzer. You can open the Object Search dialog box by pressing the F4 key or by
choosing Object Search from the Tools menu and then Open. You can open
multiple Object Search dialog boxes at the sam e time. The dialog box lets you
search for any object or subset of objects, such as views or stored procedures, by
nam e or even a part of a nam e. Figure 1-13 shows an excerpt from the results in
a search for any type of database object that begins with Categ in any database
on the currently connected SQL Server instance. As you can see, objects
beginning with Categ for their nam e are very popular in the Northwind database.
(Other databases outside the excerpt shown also have objects beginning with
Categ.)
Figure 1 -11 . An opened T-SQL script from a saved .sql file. The path and
filenam e in the title bar indicate the source of a .sql file.
Selected Other Topics
There’s lots more to Query Analyzer, but the preceding introduction equips you
for the ways in which this book exploits the tool. I n this section, I briefly highlight
a couple of my favorite other uses for Query Analyzer.
The Object Browser is a convenient tool for exploring the databases and the
objects within them on a connected SQL Server instance with a tree-type
interface. You can use this Query Analyzer com ponent to examine the database
objects within a database. You can show or hide the Object Browser by pressing
the F8 key or by choosing Object Browser from the Tools m enu and then the
Show/ Hide command. Figure 1-12 shows the Object Browser window expanded to
display the colum n nam es and data type specifications for the Categories table
(dbo.Categories) in the Northwind database. I often find it convenient to drill
down into a database design and check the spelling of colum n nam es. Being able
to quickly look up the data type for a colum n in a table is particularly convenient
when you are declaring a search param eter for a co-lum n in a table; use the
wrong data type, and you may not get a match, even with the right value.
Figure 1-12 . The Object Brow ser opened to show the nam es and data
types for the colum ns in the Northw ind database.
Figure 1 -1 3. You can use the Object Search dialog in Query Analyzer to
search for objects by nam e ( or even part of a nam e) .
Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson
Chapter 2. Tables and Data Types
This chapter targets the design and programm ing of SQL Server tables with T-
SQL (Transact Structured Query Language). SQL Server database adm inistrators
and developers use T-SQL for programm ing database administration and data
access. By data access, I mean selecting records from a database. T-SQL is
generally compatible with the SQL-92 standard endorsed by ANSI (American
National Standards I nstitute) and ISO (I nternational Standards Organization).
However, Microsoft optimized and stream lined T-SQL for use with SQL Server.
Any developer who wants to use Visual Basic .NET to build custom SQL Server
solutions will be severely handicapped without a good grasp of SQL Server data
types and tables, as well as T-SQL. Several subsequent chapters in this part of
the book will explore selected other database objects, such as views, stored
procedures, and user-defined functions, from design and implem entation
perspectives with T-SQL. The next part of the book builds on this foundation as it
dem onstrates how to create custom SQL Server solutions with Visual Basic .NET.
This chapter begins with an exploration of SQL Server data types. Next it
provides an overview of different types of tables. A series of T-SQL samples
illustrates core table design issues and solutions. These samples introduce you to
programm ing techniques for SQL Server tables. By understanding how to script
database objects, such as tables, you can readily duplicate those database
objects across multiple servers. For example, a Visual Basic developer can build a
solution on one server and then readily transport the objects for use on another
server— just by running the scripts for the objects. You can also adapt the script
from one object as a starting point for other, similar, objects. A clear
understanding of table scripting techniques will help you to automate table
design. This frees resources for focusing on the needs of clients for your
databases.
Chapter Resources
There are two key resources for this chapter. First, a SQL Server database nam ed
Chapter 02 illustrates m any of the design concepts used throughout this chapter.
Second, a collection of T-SQL sample scripts illustrates coding techniques for
creating tables and working with the resources within a table.
The Chapter’s T-SQL Sam ple Scripts
The T-SQL sample collection for this chapter illustrates key design and
implem entation issues for scripting SQL Server database objects. All the sample
scripts that you see in this chapter are available on the book’s companion CD.
The samples are all saved with the .sql extension, so you can open and run each
of them from Query Analyzer. As you learned in Chapter 1, Query Analyzer is a
graphical tool that ships with Microsoft SQL Server 2000. As you read and run the
sample scripts, you m ight find it helpful to learn more about the structure of the
Chapter02 database by browsing it with SQL Server Enterprise Manager, which
also was discussed in Chapter 1.
The Chapter’s Sam ple Database
The script in this section creates a new version of the Chapter02 database.
Subsequent T-SQL code samples will create additional tables in the database and
dem onstrate techniques for working with tables.
Prepare to create the Chapter02 database by starting Query Analyzer and
connecting to the SQL Server instance you are using. Log in as sa or with a user
ID that belongs to the sysadmin fixed server role. This book drills down on
security explicitly in Chapter 7, where you will learn how to fine-tune database
and user security settings. When users connect to a SQL Server database through
your Visual Basic .NET applications, they m ust identify them selves through the
security accounts discussed in Chapter 7. Until that chapter, using a login that
belongs to sysadmin will work for all sam ples.
Copy or type the following T-SQL script into the Editor pane in Query Analyzer,
and press F5 to run the script to create the database. Alternatively, you can open
the script directly from Query Analyzer: choose Open from the File m enu, and
then navigate to the location of the script. Notice that the first comment in the
sample is “CreateSampleDB”— the nam e of the sample file. I use this convention
for all the samples in the book to m ake it easier for you to locate and open them
from Query Analyzer.
Attaching a Database to a New SQL
Server I nstance
I regularly read on the SQL Server newsgroups of folks asking how
to attach a database to a server. These developers want to take a
database and its objects developed on one server and run them on
another server. Their need can be as simple as copying a database
application they are developing on their desktop to their laptop so
they can work on it while away from the office. Alternatively, they
may want to copy a database from headquarters or one branch
office to one or more other branch offices.
Although there are wizards for this kind of thing, it is nice to know
how to program the administration of this kind of task for your own
custom solutions. This capability liberates you from the canned
wizard solution and gives you more flexibility in how you work with
SQL Server. At its most elementary level, this can be as simple as
attaching a pair of database files to a new server instance. In the
context of this chapter, a completed version of the Chapter02
database is on the book’s CD. Therefore, you might care to copy a
version to another instance of SQL Server besides the one you use
to test the samples for this chapter. The instance can be on another
computer or the same computer.
Start to migrate the Chapter02 database by copying the
Chapter02_dat.mdf and Chapter02_log.ldf files from the CD to the
Data folder for the SQL Server instance to which you want to attach
the completed database. After clearing the read-only attribute
settings for the files, you can run the following script from Query
Analyzer. The script attaches the chapter’s two database files to the
default instance of the SQL Server to which Query Analyzer
connects. By changing MSSQL to MSSQL$MYOTHERI NSTANCE, you
can attach the database files to a SQL Server instance named
MYOTHERINSTANCE. You must copy your database files to the Data
path for the SQL Server instance in the sp_attach_db statement
before running the script.
--AttachSampleDB
--Run the script from the master database.
USE master
--Update the paths for the data and log files so they
--are appropriate for your computer.
EXEC sp_attach_db @dbname = N’Chapter02’,
@filename1 =
N’c:Program FilesMicrosoft SQL ServerMSSQLDataCha
pter02_dat.mdf’,
@filename2 =
N’c:Program FilesMicrosoft SQL ServerMSSQLDataCha
pter02_log.ldf’
The initial USE statem ent in the script specifies the source database so that the
sample runs from the SQL Server m aster database. Next the script rem oves any
prior version of the Chapter02 database on the server. This ensures that you can
always create a new copy of the database. After rem oving any prior version, the
code invokes the CREATE DATABASE statem ent. This statement assigns the
logical filenam es Chapter02_dat and Chapter02_log to the data and log files for
the database. Although your SQL Server databases can have m ore files, these
two are necessary for populating a database and perform ing backup operations.
Update the operating system file paths so that they are appropriate for your
computing setup.
--CreateSampleDB
--Execute statements from the master database.
USE master
GO
--Drop any prior version of Chapter02 database.
IF EXISTS (SELECT *
FROM INFORMATION_SCHEMA.SCHEMATA
WHERE CATALOG_NAME = N’Chapter02’)
DROP DATABASE Chapter02
GO
--Create new version of Chapter02 database.
CREATE DATABASE Chapter02
ON
(NAME = Chapter02_dat,
FILENAME =
’c:program filesmicrosoft sql servermssqldataChapter02_dat.m
df’,
SIZE = 1)
LOG ON
(NAME = Chapter02_log,
FILENAME =
’c:program filesmicrosoft sql servermssqldataChapter02_log.l
df’,
SIZE = 1,
MAXSIZE = 5)
GO
Data Types for Tables
Tables are the building blocks for SQL Server applications because they store the
data for the entities that an application models. Likewise, colum ns are the
building blocks of tables because tables store their data as colum n values. SQL
Server applications can often have tables with numerous rows, so it is important
to specify the data type for columns to ensure that they use the m inim um
amount of storage. When you specify the data type, you are indicating the kind of
data that the colum n is going to contain. Making these assignm ents correctly
speeds the perform ance of your SQL Server applications while also conserving
storage space. I n addition, the validity of your database m odel for a real-world
system can depend on the use of proper data types.
In many circumstances, your applications can denote data with one of the data
types built into SQL Server— the system data types. When your application needs
more definition than these system data types allow natively, you can create user-
defined data types that refine the system data types. However, your ability to
fashion valuable user-defined data types depends on your grasp of the system
data types.
If you are fam iliar with data types, you may want to skip this section and refer to
it as needed. But if you are new to SQL Server programm ing or need a refresher
on data types, read on.
System Data Types
It is useful to think about the system data types in six groups. I n addition to the
six hom ogeneous categories, there is a collection of special, or m iscellaneous,
system data types. The six hom ogeneous groups of data types pertain to:
• Character data
• Unicode data
• Num eric data
• Monetary data
• Date and Tim e data
• Binary data
Character Data
Character data consists of alphanum eric character sequences. Therefore, you can
represent any combination of numbers and words with character data, such as
“123 Mulberry Lane”, “$1,000,000”, “Your nam e goes here: ” or “Rick Dobson”.
SQL Server has three character data types: char, varchar, and text. The following
table briefly summarizes them.
'DWD
7SH
1DPH
'DWD7SH'HVFULSWLRQ
char For fixed-length character data up to 8000 characters. Use char(n) to
specify, with n as the number of characters. The storage size is n bytes.
Appropriate when all the column values are the same length (or when
this is very nearly true).
varchar For variable-length character data up to 8000 characters. Use
varchar(n) to specify, with n as the maxim um number of characters.
The storage size for any varchar colum n value is the actual size, where
1 byte equals 1 character. Appropriate when there is substantial
variability in length between colum n values.
text For variable-length character data that can grow to 231
-1
(2,147,483,647) characters in the SQL Server instance’s code page
format. Although som e of these code pages perm it double-byte format
for representing characters, the length of a text data type colum n value
is still the number of characters, where 1 character equals 1 byte.
SQL Server supports im plicit and explicit conversion between data types. SQL
Server handles implicit conversions automatically; you use the CAST and
CONVERT functions to convert between types explicitly. The CONVERT function is
a proprietary extension of the CAST function that offers extra conversion
capability not available from CAST, which is SQL-92 compliant. See the “CAST
and CONVERT” topic in SQL Server Books Online for m ore detail on conversion
between SQL Server data types.
Im plicit conversions don’t depend on the transform ation of a value by the
CONVERT or CAST function. Im plicit conversion also applies to the conversion of a
result from com bining or comparing two or more values with different data types.
A variety of Books Online topics clarify implicit conversion, including the “CAST
and CONVERT” topic. For example, see the “Data Type Conversion,” “Data Types
and Table Structures,” and “Data Type Precedence” Books Online topics. You can
use the Search tab in Books Online to search for these topics. The Books Online
search engine will often return multiple topics for any search string, even when
you specify a precise search topic title. Scan the list of titles returned by the
search engine for the exact one you seek.
Unicode Data
Unicode is a 16-bit character encoding standard. SQL Server data types for
Unicode correspond to SQL character data types— nchar, nvarchar, and ntext for
fixed-length, variable-length, and very long Unicode data. One key distinction is
that the Unicode format for translating bits to characters relies on a single
standard translation table that uses 2 bytes per character. The character data
formats use a collection of different code pages most of which assign 1 byte per
character. This distinction gives Unicode format the capacity to represent m ore
than 65,000 characters, while non-Unicode character data typically represents
only 256 characters at a tim e (or per code page). The Unicode codes that have
been assigned represent characters in m ost of the written languages of the world.
Character data uses system-level tables called code pages to determ ine how to
translate bits to characters. Different countries can rely on different code pages to
represent their character set. For applications that run in many different
countries, it can be challenging to find a single code page with valid and
consistent bit-to-character translations for all languages. Using Unicode data
resolves this problem because its code page accommodates 216
characters. The
price for this easier cross-country applicability is that each character has a size of
2 bytes instead of the 1 byte per character. As a result, the maxim um number of
characters for Unicode data types is half that of corresponding character data
types.
The following table sum marizes the three Unicode data types. These data types
align with the character data types, but they have different length and
applicability.
'DWD7SH
1DPH
'DWD7SH'HVFULSWLRQ
nchar For fixed-length character data up to 4000 characters in length with a
Unicode data format. Use nchar(n) to specify, with n as the number of
characters. The storage size in bytes equals twice the number of
characters. Corresponds to the char data type in terms of applicability
except for its broader usefulness for representing characters from
multiple languages.
nvarchar For variable-length character data up to 4000 characters in length. Use
nvarchar(n) to specify, with n as the maximum number of characters.
The storage size for any nvarchar colum n value is the actual size,
where 2 bytes equal 1 character. Corresponds to the varchar data type
in terms of applicability except for its broader usefulness for
representing characters from m ultiple languages.
ntext For variable-length character data that can grow to 230
-1
(1,073,741,823) characters in the Unicode code page format.
Corresponds to the text data type in term s of applicability except for its
broader usefulness for representing characters from multiple
languages.
Note
In the case of column data type specifications, precede the
character data type name with an n to denote the matching
Unicode data type name. Represent character constants in
SQL Server with single-quotation mark delimiters. Use a
leading N to represent a Unicode constant. For example, a
character constant appears as ‘my character constant’ .
However, the matching Unicode equivalent appears as N’my
Unicode constant’ .
Num eric Data
Num eric data consists of numbers only. You can perform arithm etic operations on
numeric data, and you can compare num eric values along a num eric scale, which
can differ from comparisons based on collations for character data and Unicode
data. SQL Server has three general categories for num eric data: integer data,
decimal data, and approximate data. Within each of these categories, there are
one or more specific data types. Beyond that, the num eric data categories denote
different classes of num bers or ways of representing numbers.
I nteger Data
Integer data types denote values that SQL Server represents exclusively as whole
numbers. The integer data types include tinyint, smallint, int, and bigint. The data
types differ primarily in the magnitude of the number that they can represent,
but the tinyint data type differs in that it cannot represent negative values as can
the others. I nteger data types, particularly int, are comm only used along with the
IDENTI TY property to specify autom atically incrementing colum n values that
serve as the primary key for a table.
The next table lists the integer data types along with brief summaries of their
capabilities. Your applications should generally use the sm allest data type
possible. However, use a data type with sufficient range for your needs because
SQL Server rejects column values outside the limits for a data type. Calculations,
such as aggregations in views, work differently for tinyint and smallint values. I n
these cases, SQL Server automatically prom otes the return value to the int value
range. Therefore, the sum of a set of tinyint colum n values can exceed 255, but
no individual tinyint colum n value can exceed 255.
The tinyint/ smallint promotion policy doesn’t apply to calculations based on int
colum n values; SQL Server doesn’t automatically promote a return value outside
the int lim its— even if the result is within the bigint limits. I nstead, SQL Server
returns an error. I n addition, the bigint data type doesn’t work with all functions
that the other integer data types can use, and there are special functions for
selected tasks, such as counting instances and returning rows affected by
queries, in which the quantities exceed the int range to fall in the bigint range.
See the “Using bigint Data” topic in Books Online for m ore detail on the special
restrictions that apply to the bigint data type.
'DWD7SH
1DPH
'DWD7SH'HVFULSWLRQ
tinyint For values in the range 0 through 255. Each tinyint column value is 1
byte long.
smallint For values from -215
(-32,768) through 215
-1 (32,767). Each smallint
column value consum es 2 bytes of storage.
int For values from -231
(-2,147,483,648) through 231
-1 (2,147,483,647).
Each int column value requires 4 bytes of storage.
bigint For values from -263
(-9,223,372,036,854,775,808) through 263
-1
(9,223,372,036,854,775,807). Each bigint column value requires 8
bytes of storage.
Decim al Data
The decimal data category is a single num eric category with two equivalent SQL
Server data types: num eric and decimal. You can use them interchangeably, but
decimal is probably the more comm on data type nam e. Like the integer data
types, the decim al data types precisely represent values. However, decimal data
types differ from integer data types in three ways. First, decim al data type values
allow for places after the decimal. (Recall that integer data types restrict you to
whole numbers.) Second, decim al data type specifications permit a variable
precision (or total number of digits). The total number of digits, which can range
from 1 through 38, includes digits to the right and left of the decimal point. Third,
you can designate a decimal data type for a colum n with variable scale (or digits
to the right of the decimal point).
Note
The decimal data type in SQL Server 2000 and the Decimal
data type in Visual Basic .NET aren’t the same. The Decimal
data type in Visual Basic can represent numbers with values
from 1 through 28 digits to the right and left of the decim al
point. This distinction (1 through 28 vs. 1 through 38) is
important. Unless proper precautions are taken, you can
encounter overflow errors as you extract column values with
a decimal data type from a SQL Server table into your Visual
Basic .NET application. If you know the numbers in the SQL
Server table exceed the values that Visual Basic .NET can
represent with its Decimal data type, consider representing
the SQL Server decimal data type values with another data
type in Visual Basic .NET, such as Double, which has a range
from -1.79E + 308 through 1.79E + 308.
Designate a decimal category value with decim al(p,s) or num eric(p,s). The p
value represents the precision; the s value denotes the scale. The precision m ust
be less than or equal to 38 but greater than or equal to the scale. The scale m ust
be less than or equal to the precision, but the scale has to be greater than or
equal to 0. The maxim um data range for decim al type values is from -1038
+ 1
through 1038
- 1. This range substantially exceeds the limits of any integer data
type. The sam e holds true for the two m onetary data types that SQL Server
offers. (We’ll review these shortly.)
Note
Columns with the decimal data type specification can also
serve as an auto-incrementing primary key when you assign
an IDENTITY property to the column. Set the scale to 0 for
this application of the data type.
The length in bytes for the decimal data type specification depends on the
precision. The following table summarizes the relationship between storage
requirem ents and precision for decim al data types.
3UHFLVLRQ 6WRUDJH%WHV
1–9 5
10–19 9
20–28 13
29–38 17
Approxim ate Data
All the prior num eric data types precisely represented data values. This avoids
rounding error. The two approximate data types allow you to represent data
values without perfect precision (but extrem ely close to the exact value). I n
exchange for reduced precision requirem ent, the approximate data types offer a
much wider range than the previous data types. When you need to represent
numbers beyond the range of the preceding num eric category data types, the
approximate data types offer a viable alternative (for example, in engineering
applications working with very large or sm all values). Approxim ate data types
also enable your applications to use less storage space when reduced precision is
acceptable for your needs.
The two SQL Server approximate data types are real and float. The real data type
offers the smaller range and precision, but it requires just 4 bytes per data value.
Its range extends from -3.40E + 38 through 3.40E + 38. The float data type
extends from -1.79E + 308 through 1.79E + 308, but each float data type value
requires 8 bytes of storage. Therefore, the float data type offers increased range
and precision relative to the real data type, but float data type values consume 4
more bytes per column value. Both data types follow the IEEE (I nstitute of
Electrical and Electronic Engineers) 754 specification for approximate data types.
SQL Server uses the round up mode, which is one of four rounding m odes in the
754 specification.
Monetary Data
SQL Server has two data types for representing m onetary data. Both are accurate
to the nearest ten-thousandth of a monetary unit. The smallmoney data type has
a range from -214,748.3648 through 214,748.3647. SQL Server requires 4 bytes
of storage for each value with this data type. The money data type has a range
that starts at -922,337,203,685,477.5808 and runs through
922,337,203,685,477.5807. This data type consumes 8 bytes of storage for each
colum n value. With either data type, you can use a currency symbol, such as $,
and a decimal point when inputting values, but you shouldn’t input values with
commas. I n other words, use $1234.5678 instead of $1,234.5678.
As you can see, the two m onetary data types are two possible variations of the
decimal data type in term s of its precision and range. For example, you can
represent smallmoney data types with decimal(10,4). The m oney data type has
decimal(19,4). When you need to represent m onetary data with other formats,
use alternative decimal specifications, such as decim al(19,2) or decimal(38,2).
Date and Tim e Data
SQL Server has two data types for internally representing date and tim e values.
These data types differ in precision as well as range. Before diving into the details
of each data type, note that SQL Server data types for date and time values
always contain both a date and a tim e value. I n addition, while SQL Server uses
one of two internal form ats for storing date and time values, it displays date and
time values as strings. I n addition, you will frequently input a new date or tim e
colum n value as a string. When designating a date or a tim e value with a string,
you can designate just the date, just the tim e, or both the date and the time.
The smalldatetime data type has the shorter range of the two data types for
dates and tim es. This data type includes dates from January 1, 1900, through
June 6, 2079. Within any given day, smalldatetime data type values represent
time from 12: 00 A.M. (midnight) through 11: 59 P.M., to the nearest minute. The
smalldatetime data type rounds down to the nearest m inute for all values of
29.998 seconds or less. Conversely, it rounds up to the nearest m inute for all
values of 29.999 seconds or m ore. You can designate a datetim e value with a
character string to the nearest one-thousandth of a second, such as '
January 1,
1900 12: 00: 29.998'
, for implicit conversion as input to colum ns with a small-
datetim e data type specification. Each smalldatetime colum n value requires 4
bytes of storage— two for the date and two for the tim e.
The other data type for date and time values is datetim e. Values in datetim e
format can range from January 1, 1753, through Decem ber 31, 9999. As with the
smalldatetime data type, the datetim e data represents tim e from midnight.
However, the precision is to the nearest 3.33 m illiseconds. Therefore, you can
represent the first tim e value after m idnight as '
00: 00: 00: 003'
. SQL Server
rounds datetime values internally to the nearest millisecond within its precision.
For example, tim e values to the nearest millisecond progress from '
00: 00: 00: 000'
to '
00: 00: 00: 003'to '
00: 00: 00: 007'
. The datetime data type specification
consum es 8 bytes of storage— 4 bytes for the date and 4 bytes for the time.
Binary Data
Binary data represents data in its native binary format. For example, a GUID, or
globally unique identifier, appears as a 16-byte binary data stream. SQL Server
represents each byte with two hexadecim al numbers. The decimal num ber 17, for
example, appears as 11 in hexadecimal format, which corresponds to 00010001
as a byte. Hexadecimal formatting uses the letters A through F to denote the
decimal values 10 through 15. Therefore, the hexadecimal number 9F translates
to 159 in decimal format, or 10011111 as the bits for a byte. SQL Server
frequently denotes hexadecim al values for input and display with a leading 0x;
that is, a zero followed by a lowercase x. Of course, the internal representation
contains just the binary representation for data.
There are three data types for binary data in SQL Server. When you are working
with data strings of 8 KB or less, use either binary or varbinary. For longer binary
data streams, such as Word docum ents or Excel worksheets in Office 97 or Office
2000, use the image data type. The following table summ arizes the three binary
data types.
'DWD7SH
1DPH
'DWD7SH'HVFULSWLRQ
binary For fixed-length binary data up to 8000 bytes in length. Use binary(n)
to specify, with n as the number of bytes. The storage size is n bytes.
Appropriate when all the column values are the same length.
varbinary For variable-length binary data up to 8000 bytes in length. Use
varbinary(n) to specify, with n as the maximum number of bytes. The
storage size for any varbinary colum n value is the actual size of a bit
stream in bytes. Appropriate when not all colum n values are the sam e
length.
image For variable-length character data that can grow to 231
-1
(2,147,483,647) bytes. Use this data type when your binary data
exceeds 8 KB for any column values. Although the data type’s name is
image, it accomm odates any binary data, including bitmap or GI F
image files as well as Word .doc files.
Special System Data Types
Four remaining system data types complete the set available for specifying
colum ns in a table: timestamp, bit, uniqueidentifier, and sql_variant. These data
types don’t fit into any one category. This section addresses each of the data
types individually.
The timestamp data type is a binary variable that tracks the latest addition or
revision of a row throughout a database. I t is a sequential number— somewhat
like an autonumber in Access or an integer with an IDENTITY property setting in
SQL Server. However, it pertains to an entire database instead of a single table
within a database. Whenever a user adds a new row or revises a value in a row of
a table with a tim estamp colum n, the timestam p colum n value increases by 1.
SQL Server represents this tim estamp value as an 8-byte binary value. I f the
largest tim estamp value throughout any row in any table of a database is
0x13579BDF, the next tim estamp value will be 0x13579BE0.
Note
Columns declared with a timestamp data type don’t contain
datetime or smalldatetime values. Microsoft announced its
intention to reference the timestamp data type as the
rowversion data type in future SQL Server versions.
The bit data type is for representing True/ False or Yes/ No data. In SQL Server, a
bit data type with the value 1 is equivalent to True or Yes. The bit value 0
corresponds to False or No. You can, optionally, make a bit data type nullable so
that it can have the value 0, 1, or NULL. Values in bit form at consum e 1 bit, and
SQL Server packs bit data values 8 bits to the byte to conserve space. Therefore,
1 through 8 bit data type columns in a row require 1 byte of storage. The ninth
through the sixteenth bit data type colum ns add a second byte of storage for
each row.
The uniqueidentifier data type specifies a 16-byte GUI D. Since a GUI D is unique
in space and tim e, the uniqueidentifier is a candidate for identifying rows across
multiple installations of SQL Server, such as by state in the United States or by
country. However, because of its size, using a uniqueidentifier can slow an
application and consum e storage disproportionately. The severity of this
uniqueidentifier weakness escalates with the number of rows in a table. Consider
using an int (or even a bigint) colum n with an I DENTI TY property along with a
second column to denote place. This alternative approach to uniquely identifying
records at m ultiple locations can m ake an application run faster and consume less
storage. Also, the uniqueidentifier doesn’t work well for the full range of SQL
Server functions; see the “uniqueidentifier” and “Using uniqueidentifier Data”
topics in Books Online for more detail.
A sql_variant data type specification enables a colum n in a table to accept a
mixed collection of data values based on any other system data type except text,
ntext, timestamp, image, and sql_variant. All other system data types require the
values in a colum n to be of one data type. You can’t enter character data into a
colum n with an int data type. With a sql_variant data type specification, a single
colum n can contain char, int, and datetime data values all in a single colum n. The
sql_variant data type name derives its nam e because of its sim ilarity to the Visual
Basic Variant data type.
The m ixed data type values in a sql_variant column can cause its values to
behave differently when you’re comparing sql_variant values with values of
another data type or when you’re sorting a table by the values in a sql_variant
colum n. See the “Using sql_variant Data” topic in Books Online for m ore details
on this topic.
'DWD7SH1DPH 'DWD7SH'HVFULSWLRQ
timestamp The timestamp data type has a binary(8) data form at unless you
make it nullable. A nullable timestamp data type has a
varbinary(8) data format. SQL Server automatically generates
timestamp values; your application or your users have no need to
populate a tim estamp colum n.
bit Prim arily for modeling attributes that can have one of two states.
However, the data type also does perm it NULL values. SQL
Server optim izes storage of bit data type values so that the first 8
take up to 1 byte, the next 8 a second byte, and so on.
uniqueidentifier A 16-byte binary num ber that represents its value as 32
hexadecimal characters. The format for displaying the -
hexadecimal characters is xxxxxxxx-xxxx-xxxx-xxxx-
xxxxxxxxxxxx. Use the NewID function to generate a new
uniqueidentifier. You can specify a uniqueidentifier value either
with a character string representing the 32 hexadecimal
characters or with a binary number. However, always use the
NewID function when you must ensure the uniqueness of the
uniqueidentifier value.
sql_variant For storing multiple other kinds of data type values in a single
column. This SQL Server data type bears a resemblance to the
Visual Basic Variant data type.
Note
Two additional SQL Server types do not represent individual
numbers or string values. These are the table and cursor
types. The table type can represent a whole result set of
values, such as a table returned by a user-defined function.
Chapter 5 demonstrates the use of this SQL Server type. The
SQL Server cursor type refers to server-side cursors. Many
developers prefer to avoid this type because it can degrade
database performance.
User-Defined Data Types
User-defined data types enable you to define custom data types based on system
data type and nullability. You and your developer team can then apply these
user-defined data types in m ultiple tables throughout a database. The scope of a
user-defined data type is the current database, but you can copy the script
defining a user-defined database to other databases.
Use the sp_addtype and sp_droptype system stored procedures to add and drop
user-defined data types to and from a database. When you add a user-defined
data type with sp_addtype, specify its name, base data type, and nullability by
position or with param eter nam e assignments. After creating a user-defined data
type, you can assign it to table colum ns throughout a database. If you add a
user-defined data type to the m odel database, every new user-defined database
will have the user-defined data type. This is because SQL Server uses the model
database as a starting point for all user-defined databases. The sp_droptype
system stored procedure can generally remove a user-defined data type from a
database, but this system stored procedure won’t succeed if any tables exist with
colum ns defined by the user-defined data type.
Note
System stored procedures, such as sp_addtype and
sp_droptype, gain focus as a general topic in Chapter 4.
The sp_addtype system stored procedure allows you to specify a user-defined
data type in terms of its base data type. For exam ple, you can designate a postal
code data type with a char(5) or a char(9) base data type. However, users can
still enter values other than numbers in the postal code character fields. To
specify constraints that apply to user-defined data types, designate a SQL Server
Rule object and bind the rule to the user-defined data type; use the sp_bindrule
system stored procedure to bind a rule. Then developers can specify new tables
with columns specified by user-defined data types that convey the rule. This
approach for applying rules bound to user-defined data types works for the
creation of new tables but not for the modification of existing colum ns in existing
tables. For implem entation details of user-defined data types, see the Books
Online topics for sp_addtype, sp_droptype, and sp_bindrule.
Note
Examine the pubs sample database in Enterprise Manager for
several examples of how to apply user-defined data types in
a database.
Scripting Tables
The “Data Types for Tables” section earlier in this chapter described the most
fundam ental elem ents of a table. However, it didn’t demonstrate how to apply
those elements to the construction of a table. This section introduces T-SQL
statements and syntax rules for creating tables. The section also exam ines issues
relating to the processing of selected data types and the modifying of a table’s
design.
Creating a Table
You use the CREATE TABLE statem ent to create a new table. Before invoking the
statement, you must designate a database to hold your new table. Specify this
database with the USE statement. The following sample script assigns its new
table, EmailContacts, to the Chapter02 database; recall that the “Chapter
Resources” section includes a script for creating a fresh copy of this database.
Within the CREATE TABLE statem ent, you can specify colum n nam es for the table
along with data types and other settings for each colum n. The script creates a
table nam ed EmailContacts with four colum ns named ContactID, FirstName,
LastNam e, and Email1. The ContactID column serves as a primary key. The
colum n’s specification includes a name (ContactID), a data type (int), and a
specification for its nullability (NOT NULL); and the last keyword designates the
colum n as a primary key. Because the table includes additional columns, the
colum n declaration ends with a comma.
The remaining three declarations within the CREATE TABLE statement specify
colum ns for holding contact data. Each of these declarations begins with a colum n
nam e followed by a data type and a nullability assignm ent. A comma separates
the declaration for each colum n. I n contrast with the colum n serving as the
primary key for the table, the three colum ns for storing contact data can be null.
This allows a user to create a row for a contact at one tim e and then populate the
row at a later tim e. SQL Server has a default setting for the nullability of colum ns
that you can configure. The default configuration is for ANSI compatibility, which
allows nulls for new colum ns. Nevertheless, it is good practice to designate the
nullability of colum ns explicitly.
--CreateEmailContactsTable_01
--Execute statements after USE from Chapter02 database
USE Chapter02
--Create EmailContacts with three columns.
CREATE TABLE EmailContacts
(
ContactID int Not Null PRIMARY KEY,
FirstName nvarchar(20) NULL,
LastName nvarchar(35) NULL,
Email1 nvarchar (255) NULL
)
GO
The script will work the first tim e you run it. However, if you try to run the script
a second tim e, it will fail with a message rem inding you that the EmailContacts
table is already in the database. I n order to rerun the CREATE TABLE statement
successfully, you can conditionally drop the Em ailContacts table. You need to
drop the table conditionally because the DROP TABLE statement will fail if the
table isn’t already in the database. While you’re editing the preceding script, it
might be nice to add some data and then run a simple SELECT query to see how
to insert and retrieve data from the table. The next script dem onstrates
techniques for achieving these results.
This next script illustrates broad design issues for running T-SQL scripts in Query
Analyzer. For example, the USE statem ent designates a source database to use
for running the statem ent. USE isn’t a T-SQL statement; rather, it is a keyword
for Query Analyzer that instructs it to connect to a database on the server for the
current Query Analyzer session. I f the database doesn’t exist on the connection,
Query Analyzer returns an error m essage. Notice also that batches of T-SQL
statements are delim ited by the GO keyword. This is a keyword for Query
Analyzer as well. The GO keyword instructs Query Analyzer to interpret and run
the preceding T-SQL statements. Position the GO keyword in scripts to ensure
that a set of statements will run before you start another set of statements. This
keyword is convenient for isolating errors.
After the USE statem ent, the script tests for the prior existence of the
Em ailContacts table. I f it does exist in the current database, the script invokes a
DROP TABLE statem ent to rem ove the prior version of the table. An IF EXISTS
statement based on an INFORMATI ON_SCHEMA view is a common m eans of
testing for the existence of a database object. I NFORMATI ON_SCHEMA views
return m etadata about m any classes of SQL Server database objects besides
tables. A subsequent section dwells on this topic more specifically.
The CREATE TABLE statement is identical to the preceding T-SQL listing.
However, in the context of this sam ple, you can rerun the script repeatedly
without encountering an error message about the object already existing. After
creating the table, the following listing populates the table with two rows. I t uses
the INSERT I NTO statement to add rows. Because these statements designate
colum n values for all the table’s colum ns in the order in which they appear in the
table, the statem ents can simply reference the VALUES keyword followed by the
colum n values for a row.
--CreateEmailContactsTable_02
--Execute statements after USE from Chapter02 database.
USE Chapter02
GO
--Remove prior version of EmailContacts if it exists.
IF EXISTS
(
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = ’EmailContacts’
)
DROP TABLE EmailContacts
--Create EmailContacts with three columns.
CREATE TABLE EmailContacts
(
ContactID int Not Null PRIMARY KEY,
FirstName nvarchar(20) NULL,
LastName nvarchar(35) NULL,
Email1 nvarchar (255) NULL
)
GO
--Populate EmailContacts and run a SELECT query.
INSERT INTO EmailContacts
VALUES(1,’Rick’, ’Dobson’, ’rickd@cabinc.net’)
INSERT INTO EmailContacts
VALUES(2,’Virginia’, ’Dobson’, ’virginia@cabinc.net’)
SELECT * FROM EmailContacts
GO
A SELECT statement closes the script. When the SELECT statement runs, Query
Analyzer displays the result set in the Results pane, as shown in Figure 2-1.
Figure 2 -1 . The result set from the script to create, populate, and list
values for the Em ailContacts table.
View ing Metadata
Metadata is the information about data, such as a database server and its
objects, including databases, tables, and keys. So far, this chapter has reviewed
two main T-SQL samples. One of these created a database— Chapter02. The other
created a table— EmailContacts—within the database. I n turn, the table has
several colum ns, and one of those colum ns is defined as a primary key. I t is often
useful to be able to generate reports that contain information about the contents
of a database server and its objects. For example, the previous sample showed
that determ ining whether a table already existed in a database would allow your
application to avoid an error— trying to create a new table with the sam e name as
an existing one. SQL Server I NFORMATION_SCHEMA views can derive this kind of
information for your applications. This section exam ines this capability by
dem onstrating it.
The following T-SQL script includes four batches of statem ents— each terminated
by the GO keyword— that illustrate different uses and form ats for deriving
metadata with INFORMATI ON_SCHEMA views. The initial batch dem onstrates the
syntax for reporting the databases within a connection. I n this case, the
connection is the one based on your login to Query Analyzer and the master
database for the SQL Server instance. The master database is one of the system
databases that SQL Server creates when you install it. This database is vital to
the proper operation of a SQL Server instance. One function of this database is to
track information about all the databases on a SQL Server instance. The
SCHEMATA view of the I NFORMATI ON_SCHEMA returns a high-level summ ary of
that information.
The next batch of T-SQL statements begins by changing the context for the
statements from the master database to the Chapter02 database. This batch
returns all the colum ns from the TABLES view of the INFORMATION_SCHEMA for
which the table’s nam e doesn’t begin with either sys or dtp. While users can
create tables with nam es that begin with either of these character strings, SQL
Server uses tables beginning with these characters to m anage a database.
Therefore, excluding tables that begin with those characters can return
information about user-defined tables. Of course, if your application creates any
tables beginning with these prefixes, they won’t appear in the result set for the
TABLES view.
Note
The TABLES view for INFORMATION_SCHEMA returns
Random documents with unrelated
content Scribd suggests to you:
“My dearest Peter,—I am sending this letter to you by your father,
because I want it to reach you without fail. Letters by post go wrong
sometimes, and I don’t want this to go wrong. When I have finished it, I
shall put it into his despatch-box myself.
“When your father comes back from his visit to you and Silvia, he will
not find me here. It is no use mincing words, so I will tell you straight out
that I can’t stand him any longer. It would not have answered my purpose
just to go away from him for a month, for I should have felt all the time that
at the end of a month I should have to come back; I should have been on the
end of the string still. As it is, I shall stop away just as long as I choose. I
shall be free. I want a holiday without any tie whatever. When I mean to
come back (if I do) I shall write to him and ask him if he will take me back.
I don’t know how long it will be before I want to. It might be a fortnight, or
it might be a year, or it might be never. I shall simply stay away from him,
at some pleasant place which I have selected, until I feel better.
“While you were living with your father and me I could just get along;
but since you have gone I can’t get along at all. We weren’t much to each
other, for all my individuality—isn’t that what they call it?—had long ago
been hammered back into me. I was like a small person in a large suit of
armour. But somehow you were a part of me, and while you were there I
couldn’t go away.
“I ask you, my dear, not to make any attempt to find me, and I want you
to persuade your father not to. I shall be quite comfortable, and as I am
never ill I don’t see why I should begin to be so now. I shall go to a nice
hotel, where I shan’t have to order lunch and dinner or add up bills. It is
astonishing how many nice hotels there are, quite moderate in price, which
will just suit me.
“Now this may seem unkind, but the fact is that I don’t want to hear a
word from either you or your father. You and I have nothing in common; in
fact, I have nothing in common with anybody, and I only want to be left
alone in peace, and not to be reminded of the last twenty-five years of my
life at all. I want not to be bothered with anybody. I want to get up and go to
bed when I choose, and go for my walk, and read my book, and play
patience. You and I have never loved each other at all, so there’s no use in
pretending to be pathetic over that now. Before you were old enough to
understand, I hadn’t got any feeling left in me, or, at least, it was hammered
right inside me. If any time during these last ten years I had died, you
wouldn’t have missed me, though if you had died I should have missed you
to the extent, anyhow, of your absence making my life with your father
quite intolerable. I don’t bear him the slightest ill will, and I hope he’ll bear
me none. He has excellent servants, and they will make him quite
comfortable, which is all he wants. But I’ve got too much sense to remain
with him any longer.
“He has been saying great things lately about the immense sums of
money he will get for his series of cartoons, so that I have no scruple in
withdrawing from him the £600 a year which is my own income. I can’t be
certain, of course, whether he has not been multiplying everything by ten, in
order to glorify himself, but I suppose there is some truth in it all. Anyhow,
he has got a cheque from Mrs. Wardour for a thousand guineas, because he
showed me that. He was in great spirits that night, dancing round the table
and singing and drinking quantities of port. And that, it appears, is nothing
to what he is about to get for the rest of his great series.”
Peter took his eyes off the neatly written sheets for a moment and gave a
great gasp. The figure of his mother, as he was accustomed to behold it,
veiled and still, and sitting in shadow and never giving a sign of individual
life, had suddenly cast off its concealment and tranquillities, and stood out
violently illuminated. That smooth, polished object which had lain inert so
long in the midst of railway guides, had proved itself to be a live shell
which, without any warning or preliminary sizzling, had exploded. He
himself was unhurt, though immeasurably astonished and startled, and he
exulted in the fact that the thing had been alive after all, carrying within it
such store of devastating energy. His own marriage, his departure from
home, had set off the fuse; he had been, all unconsciously, the controlling
agent.
He dived again into this most lucid report of the explosion, observing
with regret that there were but a couple of pages more. At the moment
Silvia appeared at the door from the terrace into the drawing-room close
behind where he sat.
“Peter, is that you?” she asked.
“Yes; one minute. Or come here, Silvia. Take these sheets and read them
without saying anything till I’ve finished. It’s a letter from my mother.”
He buried himself in the remainder of the letter, hardly hearing Silvia’s
gasp of surprise as she came to the second paragraph.
“Now I want you,” the narrative continued, “to consider this before you
pass any judgment on what I have done. I am injuring nothing and nobody,
except your father’s vanity, and I have no doubt he will find some
explanation of my leaving him which will quite satisfy him. He will not be
the least less happy without me, nor will you. I have got no friends, for I am
not the sort of person who can make friends or wants them; I have been
hammered, as I have said, into myself, and I break no ties the severance of
which is painful for others any more than for me. I see so few people, and
those so very occasionally, that there need be no scandal of any kind; your
father will only have to say, about once a month, that I am on a visit in the
country, which is quite true.
“My solicitor knows where I am, and from time to time he will let you
have a note from me, saying how I am. As for news, I shall have none; I
shall take my walk, and read my book, and entertain myself very well, and I
shall be very happy, because I shall be free. I rather believe that you are
sufficiently like me to understand that, for you have always kept yourself
independent of everybody.
“Finally, I leave it to you (no doubt you will consult Silvia) as to whether
you let your father find out that I have gone when he returns home, or
whether you tell him. I think personally that it would be wiser to tell him,
because when he got home and found the few lines (not like this long letter)
which I have left for him there, just to say I have gone, he might make some
dreadful scene and upset everybody. But that I leave entirely to you.
“All the wages and books were paid up to the end of last week. The bills,
with their receipts, are in their place in the third drawer of my knee-hole
table.
“Your affectionate mother,
“Maria Mainwaring.”
Peter thrust the remaining pages into Silvia’s hand, and waited till she
had come to the end. Then they looked at each other in silence.
“I’m going to laugh,” said Peter at length.
“No, please don’t,” said Silvia. “If you do I shall cry.”
Peter tapped the sheets that lay in her hand.
“But it’s gorgeous,” he said. “I should laugh, if I did, not from
amusement—though there are amusing things—but from pleasure. Every
word in that letter is true; that’s something to be pleased about, and, what’s
more, every word in it is right. But the surprise, the wonder of it! There’s a
splendour about it!”
Silvia shuffled the sheets together, and, giving them back to him, leaned
her forehead on her hands.
“Ah, haven’t you got any tenderness?” she said. “Don’t you see the bitter
pathos of it? Your mother, you know!”
“But she says there is nothing pathetic about it,” said he.
“And that’s just the most pathetic thing of all!” Silvia said.
Peter puzzled over this a moment. He understood Silvia’s feeling well
enough, but he understood equally well, and with greater sympathy, the
answer (the retort almost) to it.
“But if she sees nothing pathetic in the situation, and I quite agree with
her, what’s the use of trying to introduce pathos?” he asked. “Pathos painted
on—like a varnish—ceases to be pathos at all; it becomes simply
sentimentality.”
Silvia turned to him like some patient affectionate teacher to a child who
pretends only not to know his lessons.
“If the absence of love in relationships like these isn’t pathetic,” she said,
“love itself is only sentimentality.”
Peter again saw precisely what she meant; he knew, too, that what she
said was true. But he knew that he, for himself, did not realize it with
conviction, with a sense of illumination.... The statement of it was just an
instance the more of Silvia’s shining there aloft of his confining cloudland.
The thought of that dealt him a stab of envy, and under the hurt of it his
spirit snapped and snarled, and retired, so to speak, into its kennel, leaving
his mind outside to manage the situation.
“Well, then, it’s pathetic,” he said, “but it has been pathetic so long that
one has got used to it. I know you’re right, but what you say hasn’t any
practical bearing——”
“Ah, my dear, but it has,” said she. “It has all the practical bearing. It is
up to you, practically, to handle it in hardness in—in a sort of ruthlessness,
or you can, recognizing what I say, deal with it tenderly.”
“By all means; but the facts aren’t new. Leave me out: let’s consider my
father and mother only. There’s the practical side of it. He’s got to be told—
at least, I suppose so. There’s no new pathos there. They’ve both been
aware of lovelessness for years. If my father takes the wounded, the
pathetic pose, it will—it will just be a pose. Frankly, I’m all on my mother’s
side. By one big gesture she has explained herself; she has made a living
comprehensible reality of herself. The Bradshaws, the railway guide
advertisements—good Lord, we know what it has all been about now!
There’s flesh and blood in it! I always respect flesh and blood!”
“But her way of doing it is an outrage,” said Silvia. “She’s your father’s
wife, after all: she’s your mother. Take your mother’s side by all means—
we’ve all got to take sides in everything: nobody can be neutral—but take
his side in her manner of doing what she has done. Sympathize with him in
that! That letter, too—will you show him the letter? The hostility of it, the
resentment!”
Peter sat still a moment fingering the leaves of the letter.
“It’s not so much resentment,” he said, “as repression. She has been
hammered back into herself all these years. Oh, I understand her better than
you. It had to happen this way. What else was she to do? Could she go to
my father and say, ‘If you can’t put some curb on your egoism and vanity, if
you continue to be such a bounder (that’s what bounders are) I really shall
have to leave you’?”
“You want to score off him, Peter,” said she. “That’s the hardness, the
ruthlessness. And you aren’t hard, my darling. Who knows that better than
I?”
“Are you sure I’m not?” he said.
She did not answer this directly.
“You’ve got to be gentle,” she said.
Peter’s fingers closed on the letter, hesitated, and then tore the sheets in
half. He tore them across yet again. “Well, he shan’t see the letter,” he said.
“It was written to me and I’ve destroyed it. But if, when I tell him, he
becomes melodramatic how can I help being what you call ruthless? He’s
so vain: you don’t know how vain he is. This will be a brutal outrage, an
attempted assassination of his vanity. But it won’t injure it. The dastardly
blow will glance aside, and he’ll put an extra bodyguard round his vanity
for the future. He’s a ridiculous person, Silvia,” said Peter in a loud, firm
voice.
Silvia gave a sigh.
“Ah, that’s better,” she said, “for you’ve torn the letter up, anyhow, and
when you said he was ridiculous, you said it, my dear, as if you were
justifying yourself rather than accusing him. Oh, you said it firmly and
loudly, but—will you mind if I say this too?—you didn’t say it so spitefully.
Now, let’s be practical. You always used to be practical, Peter. When are
you going to tell him?”
Peter looked at his watch.
“That means that if I say that I haven’t made up my mind,” he said, “you
will certainly let me know that there is plenty of time to tell him before
dinner. You want me to tell him now: that’s where we are. You call me
practical: who was ever so practical as you, when it comes to the point?”
She did not challenge that, but rather proceeded to justify Peter’s opinion
for him.
“My dear, you can put off pleasant things if you like,” she said, “because
you enjoy the anticipation of them. But where—where is the use of putting
off unpleasant things? That only lengthens a beastly anticipation.”
“He’ll make a scene,” said Peter. “I hate scenes.”
There was nothing to reply to this: it all came under the advisability,
which she had already expressed, of not putting off unpleasantnesses. So
she made no reply, and soon, for the face of her continued to push him, he
got up, still wondering if she would prefer to tell his father herself. How
strongly she wanted to do that, and how, more strongly, she refrained from
doing it, he had no idea. Her inclination, that which she combated, was
simply to go straight to those voluptuous state-rooms; but her will, her
convinced sense of what was right, of what was Peter’s own duty and
development, kept her silent.
“Oh, I am sorry for you,” she said at length, as he turned to go into the
house. “But don’t forget to be sorry for him, Peter.”
His only answer to that was a just perceptible shrug of his shoulders
(comment on the futility of her sympathy), and he walked away across the
crackling gravel.
Silvia knew how Peter’s mere presence stifled her power of judgment
with regard to him. Often and often she had to cling, desperately, to a
mental integrity of her own, in order not to be washed away by the mere
tide of her devotion to him. Her desire, not only the flesh and the blood of
her, but her very spirit, would always have surrendered to him, would have
given up herself, whole and complete, to what pleased him, to what made
him comfortable, content and happy. But somewhere between these two
apexes of physical and spiritual longing there came another peak, a mental
and judicial apex, so she framed it to herself, a thing solid and reliable, a
kind of bleak umpire that gave inexorable decisions.
Already in their fortnight of married life it had several times asserted
itself—it was her will, she supposed, clear-eyed and unbribable, which was
as distinct from the blindness of love as it was from the abandonment of
physical desire. Peter had suggested, for instance, that he should “chuck”
his work in the Foreign Office (this was the most notable of these instances)
and live, just live, now at Howes, now in London, always with her. They
would travel, they would entertain, they would have plenty of interests to
keep him busy enough. He had urged, he had argued, he had appealed to her
for her mere acquiescence, willing or not, and she had steadily and
unshakably refused to give it. Here, to-night, was another test for this
umpire of the mind. It would have been infinitely easier for her to tell Mr.
Mainwaring herself, and she knew quite convincedly that she would have
proved a far more sympathetic breaker of shocking tidings than Peter would
be. Peter would now, on his way to the state-rooms, be framing adroit
sentences, be schooling his anticipatory impatience at a melodramatic
reception of that news by his father into tolerance and gentleness. But she
had as little temptation to be intolerant or ungentle, as he had to be the
reverse; she would naturally have stood in an attitude which Peter would
find it gymnastically difficult to maintain. But he had got to do his best, not
to let her do so infinitely better.
It took but a moment’s stiffening of herself to baffle any inclination to
follow Peter and shoulder his mission for him, and her thoughts went back
to Mrs. Mainwaring’s letter and its startling effect (or want of effect) on
Peter. That had produced, so she found now when she was no longer under
the spell of his presence, a certain incredulous dismay. “You aren’t like
that,” she had assured him, but now she found herself saying, “He can’t be
like that!” He appeared to have received this intelligence with a savage, or,
if not a savage a wholly unpitiful comment. He had seemed, and indeed
seemed now, to have applauded this tragic sequel to years of resentful
companionship. He had confessed to a desire to laugh (this was the
ruthlessness). It might be that the logical result of such years was that Mrs.
Mainwaring, given that she retained any independent identity of her own,
should have been goaded into this assertion of it. It might, in the ultimate
weighing of souls, be better that she should have cut the knot like this,
rather than have been strangled by it. It was all very well for Peter to take
her side, but to take her side competently included an appreciation of what
she had suffered, and what she had failed in. Anyone could form a fair idea
of what she, as exhibited now, had suffered by the smallest recognition of
what it must have been to be tied to the present occupant of the state-rooms,
and the same exhibition showed exactly her tragic failure in allowing
herself to be driven into this hermetical compartment, where all that
reached her was the contemplation of her escape, as shown by her study of
hotels. But Peter turned over all this, which was the root of the matter, as he
might turn over the leaves of a dull book, and only saw a dramatic comedy
in it, deserving of applause for its fitness, of an exclamation, “Serve him
right!” or a laughing, “Well done, mother!” ... You couldn’t deal with
people like that; at that rate the whole world would become a relentless
machine, always grinding, always seeing others ground, always being
diverted at the pitiless revolution of the wheels. Compassion, tenderness,
these were the qualities that just saved and redeemed the world from hell, or
at least from being a wounding comedy, at which no human person could
laugh for fear of crying instead.
Silvia got up from the seat where she and Peter had read his mother’s
letter, definitely desiring to avoid the conclusion to which her thoughts were
leading her. He had wanted to laugh—that was certain, but she must forget
that. Probably he had not meant it; it was only incongruousness and surprise
(like funny things in church, which would not be in the least funny
elsewhere) which had made a spasm.... Peter assuredly was not like that
really, and the loyalty of love derided her for supposing it. He was (her
heart insisted on that) all that her love adored him for being.
The dressing bell had already sumptuously sounded from the central
turret, and, still quite ignorant of what had been the result of the disclosure,
but conscious of a yearning anxiety to know, she went up to her bedroom.
She was not so much anxious to know how Mr. Mainwaring was “taking it”
(how he “took it” seemed to matter very little), but how Peter had done his
part. Between his dressing-room and her bedroom were a couple of
bathrooms, and she heard, with a certain clinging to the usualness of life,
splashings and hissings of water coming from one of these. Whatever had
happened, there was Peter having his bath, and soon, most likely, he would
tap at her door, barefooted (he never would wear slippers as he paddled
about between his room and hers) with the blue silk dressing-gown tied
with a tasselled cord about his waist. Peter had a wondrous ritual for his
bath: he had to immerse himself first of all, and then stand on the mat while
he soaped himself from head to foot. Then, still slippery and soapy, in order
to get cold and heighten the enjoyment of the next immersion, he turned on
more hot taps, and put spoonful after spoonful of verbena salts into the
water. Then he got in again, and stewed himself in this fragrant soup. When
he was too hot to bear it any longer, he retired into a small waterproof castle
at the end of the bath, and turned on all the cold water douches and squirts
and syringes. Then, without drying himself at all, he put on the famous blue
silk dressing-gown, which had a hood to it, lit a cigarette, and tapped at her
door, to ascertain whether he could sit and finish his cigarette there. Silvia,
by this time, knew precisely the interpretation of these splashings and
hissings of water, and she would hurry up her own dressing, or slow it
down, so that she could admit him. Fresh from his scrubbings and soapings,
with the glow of the cold water on his skin, he was paganly sensuous in his
enjoyment of the physical conditions of the moment, and, sitting by her
dressing-table, talked the most amazing nonsense. He dried his feet on the
tail of his dressing-gown, he rubbed his hair on the hood of it; there was the
scent of soap and verbena and cigarette, and more piercing to her sense than
these his firm, smooth skin, the cleansedness and the freshness of him.... At
such chattering undress séances she was most of all conscious of him to the
exclusion of herself; for whereas his kiss, his caress, united her with him,
and she had part in it, when he came in thus, rough-haired, bare-legged,
wet-footed, with a smooth shoulder emerging from his dressing-gown,
while, enveloped in it, he rubbed himself dry, she felt herself merely a
spectator of this beautiful animal.
But if he came in now—he might or might not—she knew that to-night
she would be involved, so to speak, with him; his character, the essence of
him, as exhibited in such account as he might give her of the interview with
his father, would come like a cloud or a brightness that would obstruct this
purely spectator-like view of him. He would not only be the clean, lithe
animal, which, for these few minutes, she could look at without passion,
without love, without friendship even, and be absorbed in the mere joy that
there should be in this world so young and wild and perfect a creature....
There came his knock, and the usual inquiry, and he entered while her
maid, with chaste, averted face, rustled out, not waiting to be dismissed,
through the other door. He sat down in the big low chair by her dressing-
table.
“Oh, the simplest pleasures are so much the best,” he said. “Just
washing, you know, just being hungry and sleepy. I never enjoy a play or a
book or a joke nearly so much as a bath and food and getting my head well
down into the pillow. But I hate sponges. Why should I scrub my nose with
a piece of dead seaweed?”
Listen as she might, with all the delicacy of divination that love had
given to her ear, she could find in his voice no inflection, no hesitation, nor,
on the other hand, any glibness (as of a lesson learned and faultlessly
repeated) that showed that he was speaking otherwise than completely
naturally. The topics of bath and dinner and bed came to his lips with quite
spontaneous fluency, as if he had not in this last hour been the bearer to his
father of a tragic situation—one that, at least, must wound the vanity which
was so predominant a passion in him. Or had Mr. Mainwaring taken it with
the same ruthlessness, the same cynical amusement as Peter had appeared
to? Silvia could not believe that: he must have been hurt, been astounded.
But why, in pity’s name, did not Peter tell her about that interview? He must
have known how she longed to be told, whether there was good or bad to
tell....
“A revolving brush covered with wash-leather,” continued Peter, “like a
small boxing-glove. You would cover it with soap and work it with your
foot. But a sponge! Odious in texture, dull in colour, and full of horrible
dark holes which probably contain the pincers of defunct crabs and the fins
of dead fish.... Oh, by the way, I quite forgot! I did really, darling; I was
thinking so much about substitutes for sponges.”
Silvia could not doubt the sincerity of this: he had been thinking about
sponges; there was the full statement of the case. And with his
acknowledgment of that, his mere physical presence, the mere glamour of
his radiant animalism, which, after all, was part of his essence and his
charm, captured her again, whisking away for the moment all possibility of
criticism, or of wishing that he could be other than he was. She knew that
her misgivings—they amounted to that—would come flooding back, but
just for the moment they were like some remote line of the low tide, lying
miles away across shining levels.
“Oh, Peter,” she cried, “if you can design a small revolving wash-leather
boxing-glove to use for a sponge, I’ll promise to have it made for you. But
you must explain just how it’s to work....”
She broke off.
“And about your father?” she said.
“Yes, I was just going to tell you when you interrupted about the sponge-
plan,” said he. “By the way, I’ll draw you the revolving boxing-glove. A
foot-pedal below—below, mind—the water, so that your foot doesn’t get
cold. And, of course, you hold the socket of the boxing-glove—the wrist, so
to speak—in your hand, and it goes buzzing round as you work with your
foot, and you apply it, well soaped, to your face. No more dead seaweed
and lobster claws! My father now!”
Peter gathered up his knees in his arms, and sat there nursing them. His
dressing-gown had fallen off his shoulder; he looked like some
domesticated Satyr, wild with the knowledge of the woodland, but tamed to
this sojourn—enforced or voluntary—in human habitations.
“I went to him, as you told me to do,” he began.
Silvia interrupted him. She wanted him to do himself justice.
“No, my dear; you went quite of your own accord,” she said. “I never
urged you.”
Peter’s eyelids hovered and fell and raised themselves again. Often and
often had Silvia noticed that shade of gesture on Nellie’s face; but never, so
it struck her, had she seen a man do just that. The gesture seemed to imply
acquiescence without consent.
“Well, I went anyhow,” he said. “I tapped on his door, and as there was
no answer I went in. He was standing in front of that big Italian mirror in—
well, in an attitude. He is intending to paint his own portrait, when he has
finished that daub of you.”
Silvia leaned forward towards him.
“Oh, don’t talk like that!” she said. “Don’t be ironical—not that quite:
don’t feel ironical.”
Peter turned on her a face of mild, injured innocence. “I was telling you
the bald facts,” he said.
“The balder the better,” said she.
“I told him I had read my mother’s letter,” he continued, “and that there
was news in it which he had better know at once. I got him to sit down, and
I got hold of his hand. And then I told him just the fact that she had gone
away.”
Peter shifted himself a little further back in his chair and drew his legs
more closely towards him, so that his chin rested on the plateau of his
knees.
“I am not being ironical,” he said. “I am trying to tell you precisely what
happened. He made a noise—a gurgle, I think I should call it—and he asked
who the damned villain was with whom she had gone. And, to be quite
bald, that seemed to me to be unreal. I said that there wasn’t any damned
villain, and that she had gone just because she felt she must be free. He
wanted to see the letter, and I told him that I had torn it up. Then he began
throwing his hair-brushes and dress-clothes into a bag, in order to start off
and look for her, and asked me where she was. When I told him that I
hadn’t the slightest idea, he accused me of collusion with her. I merely
denied that, and said that her letter was as great a surprise to me as it was to
him.”
Peter threw away the end of his cigarette.
“Then he began to guess why she had gone. Now the point of my tearing
up my mother’s letter was that he shouldn’t know, wasn’t it, darling?”
Silvia heard herself assent. There was a sickness of the heart coming
over her, something too subtle for her to diagnose as yet.
“So he began to guess,” continued Peter, “and as he tried to guess I was
sorry for him—really sorry, you understand?”
Silvia’s heart began to thrive again.
“Yes, yes; I knew you would be!” she cried.
“He soon hit on the reason,” said Peter quietly. “There could only have
been one reason, so he thought, and it filled him with the utmost remorse.
He had been too big for her, that was what it came to—too great. He had
not, in the exaltation of his art—this is quite what he said—remembered the
limitations of—of the rest of us. She had fainted before the furnace of his
genius. It was all his fault: he hadn’t made allowance for the prodigious
strain on her—for the effects, cumulative no doubt, of the high pressure. He
strode about the room, he knocked over a chair——”
Some fierce antagonism to his narrative blazed up in Silvia. She had
wanted the facts, and here they were, but she had not allowed for the
baldness of their presentation, though she had asked for it.
“Ah, don’t talk like that, Peter,” she said. “You’re not a newspaper
reporter.”
Peter gave no reply at all. There he sat with his chin on his knees, quite
silent.... If Silvia chose to speak to him like that it was clear that she must
either go on or draw back; anyhow, the next word was with her. But all the
time that he thus tacitly insisted on his rights, resenting what she had said,
there was within him some little focus of light breaking through from her
sunlit altitudes that illumined and justified her protest. Good Lord, wasn’t
she right? Wasn’t his sentiment towards his father immeasurably ignoble
compared to the comprehension of her love? And that very fact—his own
unavowable condemnation of himself, that is to say—irritated him. If she
was like that there was no use in his continuing his story.
Silvia spoke first. Humanly, she could not bear this silence in which
Peter seemed to mock her, but divinely she must be ever so humble....
Humble? How love sanctified humility and transformed it into an ineffable
pride. She pushed back her chair and knelt by his. She longed to unclasp the
brown lean hands that enclosed him in himself and make them embrace her
also. But that might annoy Peter: there was a suggestion of “claiming” him
about it. She did not want to claim him.
“I don’t know why I spoke like that,” she said. “I asked you what
happened, and you are telling me. Will you forgive me and go on?”
Peter had never seemed so remote from her as then. In the frantic
telegraphy of her spirit, which seemed to be sending all the love that the
waves of ether would bear, there came no response from him, in spite of his
answer. “I never heard such nonsense,” he said. “We should be a pretty pair
if we had to forgive. How silly—you know it—to ask me to forgive you.”
“Show you do, by going on,” she said.
It was clear to him that what she wanted was to know not his father’s
part in this interview, but his own. Whether she liked it or not, he was going
to be perfectly honest about it.
“When he knocked over a chair and strode about,” he repeated, “and
found out the reason for my mother’s going away, I began to be less sorry
for him. He enjoyed himself: it was all a tribute to his impossible greatness.
From then onwards I acted, because he was acting. The alternative was to
tell him that my mother simply found his egoism intolerable. That wouldn’t
have done any good, so I agreed with him: that was the best thing to do. He
is in despair, a rather luxurious despair. I had either to explode that or let
him enjoy it. So it was no use being sorry for him any longer.”
Silvia broke out again; it was her love for Peter that spoke.
“My dear, you ought to have been a million times sorrier,” she cried. “If
he had been just simply broken-hearted about it, it would have been so
much better. Can’t you see that? Can you help feeling it?” She was
shedding the gleam on him.
“I know what you mean,” he said. “But I’m telling you what happened. I
was less sorry for him when he began to console himself. I suppose I’m
made like that.”
Silvia bit her lip.
“Indeed you are not,” she said. “You’re making yourself out to be hard
and unloving.”
At the moment the clang of the dinner-bell from the turret just above
Silvia’s room broke in.... The whole neighbourhood must know when the
family at Howes were warned that it was time to dress, and that three-
quarters of an hour later it was time to dine. Peter, on the first evenings he
had spent here with Silvia, had asked whether, like a Court Circular, such
publicity need be given to their domestic affairs; but Silvia, confessing
herself sentimental, had told him that her father had delighted in the
installation of that sonorous announcement. The brazen proclamation “hurt”
nobody, and “Daddy liked it.”... Certainly it served a purpose now, and
Peter jumped up.
“Lord, there’s dinner!” he said. “And I haven’t begun to dress. My
father, by the way, wants to dine upstairs. Will you tell them, as you are so
much more advanced than I, to send up his dinner? I must fly.” Peter stood
for a moment looking at her. If a situation between them had not actually
laid hold of them, it had thrown a shadow over them, and he wanted to get
out into sunlight again.
“Ah, you darling!” he said with a blend of envy and of admiration
somewhere gushing up. Envy at her immense nobility—he could think of
no other word for it—and admiration at that shrine of love which rose from
the ground of her heart. It was so beautiful an edifice: he despaired of being
worthy of it, and at times, so he confessed to himself, he wearied of its
white stainless purity.... Somehow this evening there seemed to have
opened a little crack on its soaring vault, which he must mend somehow.
“Give me a kiss, then,” he said.
CHAPTER XI
Peter, though he often hung a veil over the real workings and processes of
his mind for the benefit and admiration of others, before whom he was
anxious to present a charming appearance, was honest with himself, and
found, during the next fortnight, without any desire to dissimulate, that he
was distinctly grateful to Silvia’s insistence that he should not resign his
place in the Foreign Office, for, in the present conditions and environments
at Howes, it was certainly preferable to spend the solidity of the day in
London rather than enjoy uninterrupted leisure at home. Even then the
evenings were full of crashes and crises and intolerable ludicrousness....
His father, who still majestically occupied the state-rooms (and showed
no indications of vacating them), moved along peaks and summits of the
ridiculous, which his son really believed had never before been trodden by
foot of man. That he was enjoying himself immensely Peter made no doubt
whatever, living as he did on the heights of egoism, and free to indulge in
the most extravagant exhibition of it. His standard (victoriously raised), his
principle, his determination (announced with magnificent gestures once if
not more, during the evening) was that he would remain rock-like and
immovable, fulfilling the destiny of his own supreme will, whatever bombs
Fate might choose to drop on him. That his whole soul was bitter with
remorse for his failings and failures he did not deny. He should not have
isolated himself, as he had done, in the supernal realms of Art; he should
have remembered that he was a man as well as an artist, and had a wife as
well as the celestial mistress of his soul. He ought to have been kinder,
more tender, more indulgent to the frailty and the weakness of his
Carissima. But remorse (so waved his standard), if it was the genuine
article, must express itself not in idle repinings, but in a manful facing of
the consequences of past error. His remorse (the right kind of remorse) did
not weaken, but strengthened a man to go forward. He must not lose touch
with the joy of life; he must not get from the severe spanking that remorse
gave him only a smarting and a humiliation of the flesh. He must draw the
lesson from his punishment, and proceed more tenderly but not less
sublimely than before....
It must not be supposed that Mr. Mainwaring used such expressions as
“spanking” in actual speech, or that the ironical account of his sublimity, as
given above, was verbally his. But such, anyhow, was the manner in which
these great tirades, delivered to Peter when he went up to see his father on
his daily arrival at Howes an hour or so before dinner, impressed
themselves on his mind. Usually there was a note for him on the table in the
hall, which ran something like this:
“My Peter,—I am very low and despondent to-night, and I do not know
if I can face a sociable evening. Come up to see me, my dear, for you are
the only link which is left to me of those happy—far too happy—years, and
see if your sweet spirit will not, like David playing before Saul, exorcise the
demons of remorse and regret which shriek and gibber round the head of
your unhappy father. I have tried so hard—ah, so hard—all day not to make
myself a burden and a shadow to your dear ones, but I fear I have acquitted
myself very ill. Come and cheer me up, Peter.”
Peter, to do him justice, always went, and in the majesty of egoism, his
father, without any encouragement at all, would talk himself into a splendid
courage. At whatever cost to himself, at whatever effort from worn and
debilitated nerve-strings, he would show that there was some music yet left
in his. He would twang his mental guitar, and if the frayed string snapped—
well, his lawyer would know that his affairs were in order.... Then, sooner
or later, to Peter’s great relief, the sonorous dressing-bell would ring, and he
could go and have his bath. As likely as not, before he definitely quitted the
room, his father would allude to the magnificent 1896 port which formed so
admirable a feature in the cellars of Howes.
Usually after the bath he went in to see Silvia, but, for some reason or
other, the spontaneous nonsense of these interviews had wilted and
withered. Silvia, so it seemed to him, held herself in reserve, waiting for
something from him. Peter would give an account of his day, of his talk
with his father, and still Silvia seemed to wait. She was overbrimming with
all that she ever had for him, but, to his perception, what she waited for was
for him to turn the winch of the sluice.
Once there had been a really outrageous scene with his father, in which,
after tears, Mr. Mainwaring had slid from his chair with a groan, and lay, an
ignoble heap, upon the floor. Peter on this occasion had given Silvia a
perfectly colourless précis of the degrading exhibition, and had endorsed it,
brought collateral evidence to bear on its nature by the production of one of
the notes which usually awaited him on his return from town. He had done
that in some sort of self-justification: Silvia could not fail to realize how
trying, from their very unreality, such scenes were for him, and he gave her
also every evening a very respectable specimen of his patience with his
father. And yet he felt that Silvia was not waiting for that; it was not how he
behaved, how patient and cordial he schooled himself to be, that she waited
for. He was patient, he was cordial, and though she often gave him a little
sympathetic and appreciative word for his reward, it was no more than a
sugar-plum to a child, something to keep it quiet. What she wanted, what
she longed for the evidence of, was an internal loving driving force which
turned the wheels of the machinery of his impeccable conduct, and that he
had not got for her. He spun the wheels with a clever finger from outside.
But usually these wheels went round merrily enough. He reported his
father’s despondence; he, ever so lightly, alluded to the fact that he had
cheered him up, and his estimate was justified, for Mr. Mainwaring, on the
crashing of the dinner-bell in the turret, would sometimes announce his
progress from the state-rooms by a jubilant yodelling, and would remain for
the greater part of dinner in a state of high elation. True, he would have a
spasm now and then: if he happened to have his attention called to Mrs.
Wardour’s pearls, he might for a brief dramatic moment cover his eyes and
say in a choked voice: “My Carissima had some wonderful pearls”; but
then, true to his manly determination, he would dismiss the miserable
association and become master of his soul again.
Peter usually had a second dose of his father’s Promethean attitude later
in the evening, after Silvia and her mother had gone upstairs.
“Your treasure, your pearl of great price, your angel!” he would
ejaculate. “Her sweet pity, her divine compassion! It is she—she and you—
who reconcile me to life. But I must not bask too long in that healing
effulgence. I must get back to London; I must reinstate myself in my
desolate house, and face it all, face it all. I must stand on my own feet
again, poor sordid cripple that I am.” Then perhaps, if quite overcome, he
would bury his face in his hands, but much more usually he would stand up,
throw out his chest, breathe deeply, and draw himself up to the last half-
inch of his considerable stature.
“Work!” he said. “Work is the tonic that God puts in the reach of all of
us. Remember that, my Peter, if grief and sorrow ever visit you. But then
you have by your side the sweetest, the most sympathetic woman ever sent
to enlighten the gloom of this transitory world. So had I, by God, so had I,
and I did not recognize her preciousness and her fragility.... Enough! Silvia!
Did you notice her exquisite love towards me at dinner to-day, when for a
moment the sight of Mrs. Wardour’s pearls unmanned me?”
Peter on this occasion was lashed to the extremity of irritation.
“I don’t think I did,” he said. “I only remember that she instantly asked
you if you would have some more pheasant.”
He tried to do better than that. Certainly there was no use in saying that
sort of thing.
“But she looked at you, father,” he added hastily. “You felt what she was
feeling. Was that it?”
His father clasped his hands.
“A divine beam came to me,” he said. “A message of consolation. It
made me live again. Surely you saw its effect on me?”
Peter, at such moments, longed for his wet woods. He wanted to be by
himself, or, at any rate, with someone who could understand and enjoy this
stupendous farce. If only Nellie, for instance, had been sitting there with
him, how would their eyes have telegraphed their mental ecstasy. Silvia, at
this same moment, would not have served the purpose; she might see how
ridiculous his father was being, but below her perception of that, which
might easily have made her telegraph and smile to him, there would have
been that huge, unspeakable tenderness which, when you wanted an
answering perception of farce, would have spoiled it all. That universal
embracing compassion required salting. Before now she had seen, and
communicated to him, her sense of his father’s absurdities, but now, when
he turned trouble into an empty arena for his posturing, her sense of
comedy completely failed her. Or, if she still possessed it, Peter could not
get at it. With a flare of intuition he guessed that it might be unlocked to
him, if only he could use the right key to it. But the key was compassion,
and it was he for whom she waited to thrust it into the wards. If only he
loved they could laugh at anything together; without that the gate was
locked.
Well, if it was locked, he would enjoy his imperfect vision of what lay
within.
“Yes, I saw its effect on you,” he said, trying to imagine that Nellie was
here, enthralled and wide-eyed, “You amused us all very much immediately
afterwards by making that lovely sea-sick passenger out of an orange.
Perfectly screaming!”
His father thrust his hands through his hair; it stood up like some
glorious grey mane.
“Yes, yes,” he said, “I made an effort. I won’t, no, my Peter, I will not
lose sight of the dear gaieties of life. God knows what it costs me! Even
after a little thing like that I was more than ever plunged in the gulf of
despondency. I know how wrong I am. I must never relax my efforts; I
mustn’t give myself time to think. Work and laughter—those divine twins.”
He poured himself out a glass of whisky and soda, and chose a cigar
with proper care.
“A word or two on practical affairs,” he said, “before I go to my lonely
and wakeful bed. You will be here, I understand, till early in December. By
then I trust (I insist, indeed, on thus trusting) that I shall have schooled
myself to face the desolation of my home (what once was home) again.
May I, do you think, ask to remain here till then? I look upon your beautiful
Howes as my hospital. Soon, still maimed, still limping, still in the blue
uniform of pain, I know that I must, indeed I insist on it, face the world
again and make the best of my shattered existence. But till then? Silvia,
whom I consulted with regard to this matter, told me that you were the
master of Howes, and suggested my speaking to you about it.”
Peter saw an opportunity. His father, it is true, was an odious infliction of
an evening, but there was something to be gained by his own eager
tolerance of that, which quite outweighed the inconvenience. But he must
do more than tolerate; he must welcome; and Silvia—here was the point—
must know how splendidly he had risen to it. Before he answered he made
himself remember what the intonation of cordiality sounded like.
“But that is perfectly charming of you,” he said. “It’s lovely that the
suggestion came from yourself. She and I may be away for a day or two in
November——”
Peter did not quite know what arrangement he was to suggest about such
days when he and Silvia would be away, for instance, on their visit to
Nellie. He was spared the trouble of formulating one by his father, who
gave a great gesticulation, admirably expressive of courage.
“I will go home—home for those days,” he said. “I will, with set teeth
and firm mouth, begin to grow accustomed to my desolation and loneliness.
I will learn to bear it, taking in long draughts the inestimable tonic of work.
Peter, Peter”—and the voice shook—“when will my Carissima come back
to me?”
He was unmanned only for a moment, and his mastery of himself
returned to him.
“Was ever a stricken man so blessed by the love of his children?” he
exclaimed. “God bless you, my Peter. You are going to bed?”
The abruptness of this benediction convinced Peter that his father had
got what he wanted and had no more use for him that night, and he went
along the corridor to his room and Silvia’s. His first impulse was to tell her
how cordially, for his part, he had welcomed his father’s suggestion; the
second and wiser one was to say nothing about it. Mr. Mainwaring was sure
to make the most of it to her; he might even attribute to it that force from
inside which turned the wheels. Yes, Silvia should learn about it like that.
He let himself very quietly into his room, and undressed and went to bed
without going in to say good night to her. If he went in to see her, it was
more than likely that she would ask him whether his father had alluded to
the question of his remaining with them, and he wanted the information
concerning that to be conveyed to her by one who would give him, Peter
felt sure, a florid testimonial for cordiality. He had passed, moreover, a
monotonous and fatiguing evening, and wanted not to talk at all, but to
sleep. His father had been slightly more dreadful than usual, Mrs. Wardour
had more than ever been non-existent, and Silvia, so it struck him, had been
waiting, had been watching him, not, it need hardly be said, with fixed eye
or stealthy glances, but with some steady psychical alertness that was
incessantly poised on him. Without looking at him, without any talking to
him or talking at him, he had felt all evening—this, perhaps, had been the
most fatiguing part of it—that she had scarcely been conscious of anyone
else but him. Though her eyes were on the cards, and she ruefully
bemoaned that the goddess of piquet, whom she jointly invoked with
Peter’s father, had been so niggardly in her favours towards herself, it had
been no more than an automaton that was thus victimized to the extent of
three lost games, including a rubicon.
Peter, as he curled himself up in bed, let his mind stray drowsily over
such details of the evening, coming back always to this impression of
Silvia’s watching him. Whenever he spoke to her of his father she watched
him—seldom with her eyes—in just that manner. By aid of his quick
perception, that felt rather than reasoned, Peter had, he was sure, arrived at
what she watched for then. She watched for some token, she listened for
some inflection that indicated tenderness, sympathy, affection towards his
father. She could not have been watching for any such token as that for
herself, for he gave her those; she knew they were hers. But he had never
felt more certain about anything in these dim, vague regions of sentiment
and desire than that she wanted something more than that which he gave
her, and a certain impatience gained on him. What, after all, had been her
own first words to him when he asked her to marry him? Had not her face
flamed with the light of the beacon that welcomed him as she whispered
that all she asked was to be allowed to love him? At the time that had
seemed to him a divine intuition, one that, in a word, precisely defined her
way of love and his.
There came at that door of his bedroom which led to her room the
lightest, most barely audible of touches; he was scarcely sure whether he
had heard it or not. But he did not reply, for either it was imaginary, and
needed no answer, or it was Silvia come to see whether he was in his room
yet. In that case, even more, an answer must be withheld, for after this
evening of strain and high pressure all he wanted was to be let alone and to
go to sleep. But underneath his eyelids, not quite closed, he watched the
door which was opposite his bed and was dimly visible in the glimmer of
starshine that came in through the open and uncurtained window.
Round the edge of the door, though he had heard no click of a turned
handle, there came a thin “L” of light, which broadened until, in the shaft of
it, appeared Silvia. She held a lighted candle, which she screened from his
bed with her hand, the fingers of which, close to the flame, were of a warm
transparent crimson. Apparently his clothes, tumbled together on a chair,
first caught her notice, and from them she looked straight towards the bed.
Her face was vividly illuminated, and when she saw him lying there with
shut eyes, some radiant, ineffable tenderness came like dawn over it. Never
had he seen so selfless and wonderful a beam; she might have been some
discarnate spirit permitted to look upon him who had been the love of her
earthly heart. That, then, was how she regarded him when she thought she
was unobserved by him; he meant that to her. Next moment, round the half-
open door, the light narrowed and disappeared, and he was left again in the
glimmering dusk. Never had he seen with half such certainty and directness
what Silvia was. She had thought he was asleep, and so she could let free
her very soul. Neither by day nor night had she come to him quite like that;
all other emotions, amusement, interest, sympathy, desire, passion even, had
concealed rather than revealed her. They had been webs and veils across the
sanctuary, illumined, indeed, by the light that burned there, but still hiding
it. Now for one moment Peter had seen her with those veils drawn aside, the
holy place of her, and her love was the light of it.
He was sitting next afternoon in his room at the Foreign Office, rather
harassed by the necessity of being polite to everybody. The clerk senior to
him in his department was on leave, and it happened that an extra King’s
messenger had to be sent off to Rome, carrying a new cipher. That was a
perfectly usual incident in Peter’s routine, but this messenger was fresh to
his job, and had been in and out of the office all day, fussy and pompous,
wishing to be assured that he had got reserved compartments and a private
cabin. There was a strike on the French railways going on, and Peter had
told him that it might be impossible to secure a compartment farther than
Paris, but all that could be done had been done, and, anyhow, he would find
a seat reserved for him. Usually Peter rather enjoyed applying soothing
ointments to agitated people, and his skill as a manipulator of pompous and
fussy persons was so effective that by common consent (he quite agreeing)
tiresome officials were often turned on to him for emollient manipulation.
But to-day the telephonings and the interruptions and the pomposity and the
prime necessity of remaining dulcetly apologetic for inconveniences which
were wholly out of his control had got on his nerves, and when finally, in
answer to inquiries, it had been determined that the King’s messenger had
better, in order to secure a journey probably unvexed by strikes, go round
by Southampton and Havre, Peter had been treated to some very acid talk.
Of course, the man was an ass, no one knew that better than he, and it was
ludicrous to be infuriated by an ass.
About six then, that afternoon, Peter had done all that patience and polite
inquiries from French station-masters could do for the ass, and with
undiminished civility he had wished him a pleasant journey. In half an hour,
or, if he chose, now, since there was nothing more that could detain him, he
could telephone for his car and slide down to Howes. He did not in the least
look forward to his evening there; it would assuredly be an evening of as
high a pressure as the day had been. His father would certainly be voluble
with blessings and gratitude, and Peter hated the prospect of these
benedictions. Installed as Mr. Mainwaring now was for a couple of months
more, he would surely develop the idea which he had before now outlined,
when he assured Peter that during his daily absences in London he himself
would act as his vice-regent. He had already caused the luncheon hour to be
changed in order that he might get an extra half-hour of work into the
morning; already he had got the estate carpenter to “knock him up” an
immense frame in which he could see his second cartoon, now dismally
approaching completion, more satisfactorily displayed. And then Peter
thought of that short candle-lit glimpse last night, when Silvia had looked
into his room.
For one moment the remembrance of that magnetically beckoned him;
the next, as by some inexplicable reversal, the needle of that true compass
swung round and pointed in the opposite direction. It no longer gave him
his course back to Howes; it steadily pointed away from Howes. But even
as he told himself how inexplicable that was, his subconscious self gave a
convincing explanation of it. To hurry back to Silvia and her watch of love,
to feel that there were veils which only he could draw aside, but which,
when drawn aside by God knew what aspirations towards a light he did not
comprehend, would reveal to him again the glory of her sanctuary, was a
task for saints and lovers. He would rise to it in time, he would learn to be
worthy of an ideal that somehow, in spite of its white heat, had the chill of
asceticism frosting it; but just now he longed for ordinary, unreflective,
unstruggling human gaiety. She—Silvia—lived naturally on those heights,
just as his father lived in the cloud—or the shroud, maybe—of his own
inimitable egoism.
He was tidying his table, intending to ring up very soon for his motor to
take him back to Howes. If he started in half an hour he would have time to
see his father before dressing, and to talk to Silvia between bath and dinner.
Then he changed his mind and determined not to ring for his motor at all.
Instead he would walk back across the park—no, not across the park, but up
Whitehall, and so by streets all the way to Piccadilly. He would have time
to get a cup of tea at home and start from there immediately afterwards. The
rather longer route by the streets was infinitely preferable. There would be
crowds of ordinary human beings all the way, people not monstrous on the
one hand, so far as he knew, from swollen egoism, nor irradiated by
idealisms which made you pant in a rarefied atmosphere. There would be
just masses of people, people gay, people sulky, ugly people, pretty people,
but above all ordinary people.
At the moment when his tidying was complete, and his table ready for
his next day’s work, the telephone on his table tinkled. He resigned himself
to more inquiries from the incomparable ass, but they could not last long,
for his train left Waterloo within a manageable number of minutes. But in
answer to his intimation that it was indeed he who waited at the end of the
wire, there did not come the voice which he had listened to so often that
day, but one quite other and equally recognizable.
“Nellie?” he said.
“Yes, my dear. How lucky I am to catch you. You’re in town, then?”
“At the moment,” said he. “I’m going back to Howes in half an hour.”
“Oh, what a pity! You won’t be in town to-night, then?”
“Why?” asked Peter.
“Only that Philip and I were going to the play, and Philip’s got a cold
and thinks it wiser not to go out. I thought perhaps—just a lovely off-
chance—that you might come instead. Oh, do, Peter.”
“Hold on. Wait half a minute,” said he.
He put the receiver down on the table, seating himself on the edge of it.
Here in excelsis was precisely what he longed for. Dinner, a theatre, a talk,
all with Nellie, who represented to him (though in excelsis) the ideal
epitome of the world of humanity. He had thought a moment before, with
the sense of anticipating a “break,” the mere walk through crowded streets.
She would in this programme give him all that intimately, she would give
also the sense of intimate friendship without effort. They would jabber and
enjoy——
He took up the receiver again.
“Yes, all quite easy,” he said. “It’s late already, and when it’s late and I
can’t get down there, I can always sleep in town. Silvia and I settled that
when I began work again in this doleful office.”
Nellie appeared to laugh at that.
“Silvia evidently spoils you,” she said. “But it’s too lovely to catch you
like this. Will you dine with me at the Ritz? Seven? The play—can’t
remember what it is—begins at eight. So we shan’t have to hurry, and can
sit with our elbows on the table for a bit and talk.”
“Sit with what?” asked he.
“Elbows on the table,” said Nellie with elaborate distinctness. “No hurry
—talk.”
This time he laughed.
“Oh, don’t let’s go to the Ritz,” he said. “Come and have elbows at my
great house. I’ll go back there now and order dinner. It’ll probably be
beastly, but it’s more private. Shall we do that?”
“Much nicer,” said Nellie. “How are you, Peter? Oh, I can ask that
afterwards. Seven, then. Wardour House.”
“Yes. Give condolences to Philip. Not congratulations, mind.”
Peter hung up the receiver, and then took it off again at once in order not
to give himself time to think. There would be clamour and argument if he
thought, and he wanted nothing of that sort. Ten minutes afterwards he left
the office, having telephoned to the Jackdaw that he was detained here and
would be obliged to sleep in London.
Two months had passed since Nellie and he had met, but whatever
frontier-change of limitation or expansion had been decreed for each
severally since then, their meeting to-night had the power to put such aside,
and they hailed each other without the embarrassment of altered
circumstances. Their compasses were rigidly in accord, and as the excellent
impromptu meal proceeded the talk sailed towards northern lights, in the
direction of their steadfast needles. Soon they were sitting (at the elbow
stage) with their coffee and cigarettes, with a quiet quarter of an hour in
front of them before they need start.
“Motor at ten minutes to eight,” said Peter to the servant, glancing at the
clock. “Tell me when it comes round.”
He shifted his chair a little sideways towards her.
“Oh, this is jolly,” he said, “for we’ve gone on just where we left off.
You’re just the same. It’s two months, you know, since I set eyes on you.
Do say you’ve missed me.”
“What else did you expect?” said she. “Marriage isn’t—— Oh, Peter,
what’s the name of that river?”
“Thames?” asked Peter.
“No, the forgetting one—Lethe. Because I’m married to Philip I don’t
forget—other people. But tell me, has Silvia been giving you Lethe to drink
instead of early morning tea?”
“Not a drop. She’s given me everything else in the world.”
Nellie still had that habit of plaiting her fingers together.
“You ought to be very grateful to me,” she said. “It was I, after all, one
night at my mother’s flat, do you remember?”
“I was Jacob that night,” remarked Peter.
Nellie frowned.
“Don’t tell me how,” she said. “I want to see if we think side by side
still. Ah, I’ve got it! Philip was Esau—isn’t that clever?—and I told him I
was tired, and so you supplanted him.”
“Right. Get on,” said Peter.
“Yes, about your gratitude. It was that night that I told you to ask Silvia
to marry you. Didn’t I?”
“Yes. Thank you, dear Mrs. Beaumont,” said Peter effusively. “So good
of you to tell me.”
“It was a good idea, wasn’t it?”
Nellie’s mind stiffened itself to “attention” at that moment. Before, it had
been standing very much at ease.
“The best idea in the world,” he said.
“I’m awfully glad,” said she. “What you say, too, makes it all the more
delightful of you to stop up in town to-night, instead of going back to her.”
Though up till now they had fitted into each other with all the old
familiar smoothness, it appeared now, when they got near, in their
conversation, to what had happened to each of them (not, so he still felt,
altering them, but putting them into new cases) that there was fresh ground
to be broken; hitherto they had only picked their way over the old ground.
Nellie felt this even more imperatively than he. They had got to run the
plough (so why not at once on this admirable opportunity?) through the
unturned land.... Peter’s servant had already appeared in the doorway,
announcing the motor, and she had noticed that, but Peter had not. She
concluded from that, that he, easy as their intercourse had up till now been,
was feeling some pre-occupation. His hesitation in answering her last
acknowledgment of his amiability in remaining in town instead of going
back to Howes, confirmed that impression. Then, before the pause was
unduly prolonged, so as to amount to embarrassment, she put her word in
again.
“I appreciate that,” she said, “because it shows that the new ties haven’t
demolished the old. And on my side I admit, far more definitely than you,
that if my poor Philip must have a cold, I am glad—ever so glad—it visited
him to-night, so as to give me an evening with you.”
She swept her plate and coffee-cup aside, to make room for an advance
of the elbows.
“Oh, my dear, I have missed you,” she said. “Naturally, however
perfectly Philip is himself, he couldn’t be you. My mind—perhaps you
haven’t noticed it—has wonderfully improved these last months—I am
learning Italian, and we read Dante—but it needs just a little holiday. And
I’ve found out such a lot of things about Philip, and all of them are good,
worse luck.”
Peter looked up at her with that liquid seriousness of eye which to her
meant that he was walking in the wet woods.
“Oh, poor thing,” he said.
For some reason which she did not choose to investigate, Nellie found
that remark immensely encouraging. Certainly, a few minutes ago, she had
tried to provoke him to talk—really talk, but the ironical perfection of his
condolence, which, so she felt, saw all round what she was saying, made
her more than acquiesce in his listening instead of talking. She felt sure that
this beloved Peter understood——
“I knew you would sympathize,” she said; “but there’s my tragic
prosperity. My Philip isn’t lazy or spiteful and inconsiderate or selfish, or
bad-tempered or greedy or—or anything at all, except that he knows so
much about birds. He has taught me a lot, and he’s quite absolutely devoted
to me. He never liked anybody so much as me. But do you know, darling, to
a woman, at any rate, having a good, nice man quite devoted to her, as far
as his affections go, gives her, once in a way, a little sense of strain. She has
to find her hymn-book and sing.”
“I’ll lend you mine,” said Peter, speaking without thought, but only by
instinct.
“Thanks. When will you want it back? No; I won’t borrow it. But the
fact is, that an undilutedly good man wants something to make him fizz.
You must have humour or a vile temper or cynicism or greediness, or
something, to make you drinkable.... My dear, what am I saying?”
The clock on the mantelpiece struck the hour at which the curtain of
their play rose; but the chimes, eight sonorous thumps, preceded by the
quarters, penetrated Peter’s brain no more than the announcement of the
motor ten minutes ago had done.
“You’re talking awfully good sense,” he said. “At any rate, you’re
talking a language I can understand. You always did; we quarrelled and
wrangled, but we were on the same plane.”
“So we are now, thank heaven,” said she. “It’s time you gave me some
news, you know.”
Whatever pre-occupation it was that held Peter, he seemed to shake
himself free of it.
“Yes, I’ve got news all right,” he said. “Domestic tragedy.”
“Oh, my dear, what?” asked she. “Nothing awful?”
He seemed to know for certain that she was figuring in her mind
something about himself and Silvia. So, in the upshot, the sequel, the
development, he was. But he tested her, so to speak, over the domestic
tragedy itself.
“My mother has run away from home,” he began.
Nellie did not laugh. She only bit her tongue with firm purpose.
“Dear Peter!” she said, when she released it.
“She has simply gone,” he said. “Round about ten days ago, when father
arrived to study his first cartoon, with a view to the rest of the series—Mrs.
Wardour bought it, by the way—gracious me, what a lot we have got to talk
about.”
“Never mind the cartoon,” said Nellie with thrilled interest. “Get on with
the tragedy.”
Quite uncontrollably Peter’s mouth began to lengthen itself. He did not
quite smile, but the promise of a smile was there.
“Tragedy, then,” he said. “My mother sent me a long—oh, such a
priceless letter, to say that when my father came home again—his home, I
mean—he would find she had gone.”
The Dryad, the gay conscienceless Nellie, could not, in spite of her
improved mind, quite contain herself.
“But your mother?” she asked. “At her age? How absolutely wonderful
of her! Do you know who he is?”
Peter tried not to laugh, and completely failed in that dutiful endeavour.
She could but follow his lead, and the two, drawing psychically nearer to
each other every moment, abandoned themselves, just for natural relief, to
this irrepressible mirth.
“You are such a damned fool, Nellie,” he said at length. “Do listen: don’t
be funny. It’s quite different.”
“ ’Pologies,” said she, rather shakily.
“It wasn’t anything so romantic, but it was just as human,” said Peter.
“You know how my mother was hammered into herself—that phrase came
in her letter, by the way: it’s not original.”
“But I never guessed there was anything to hammer,” said Nellie.
“Nor did I; at least, I only half guessed. But there was. A breaking point
came, and she couldn’t stick my father any longer. She has just gone away.
Do you remember how she used always to be looking up hotels in railway
guides?”
“I remember that most of all,” said she. “Well?”
“She’s gone to one of them. She’s just gone away to be free, not to lead
somebody else’s life any more. When she has got a good breath of air, she
may, apparently, come back. But she doesn’t promise.”
Nellie had grown quite serious again.
“That’s even more wonderful of her,” she said. “She just went away
because she wanted to be herself. My dear, what a mother! And waiting till
you were married! And your father? Go on.”
This time Peter’s mouth strayed beyond the limits of mere reflective
meditation, and smiled broadly.
“He has discovered, to his complete satisfaction, why she left him,” he
said. “He knows—as if Gabriel had told him—that his tremendous
personality, his devotion to Art, all that sort of thing, was too much for her.
He reproaches himself bitterly—and oh, my dear, how he enjoys it—with
having failed to realize the frailty—not moral—the weakness, the
ordinariness of other people. She was scorched in his magnificent flames,
and escaped from that furnace with her life.”
“But how lovely for him!” said Nellie. “Lovely for her, too. But why
tragedy? You said it was a tragedy?”
His whole body gave a jubilant jerk. If he had been standing up he must
have jumped.
“Ah, you do see that, don’t you?” he cried. “I just rejoice in her! At least,
I would——”
Nellie divined perfectly well that “if Silvia understood” really completed
the sentence. But if Peter wished, for the present anyhow, to leave that
unspoken, loyalty to their comradeship prevented her from suggesting it.
Another motive, not less potent than that, dictated her silence on the point,
for she infinitely preferred that he should volunteer some such information
concerning himself and Silvia than that she should give away her
knowledge of it. Certainly she longed to know in what real relation he and
Silvia stood to each other, but it would be a tactical error (tactical was too
businesslike) to let him know that his incomplete sentence gave her so
certain a hint.
“I see,” she said quickly. “You would rejoice in her if it wasn’t for your
father.”
Until the two ultimate words of that were spoken Peter’s eyes had been
bright and expectant. He evidently waited for the termination which she had
refused to utter. When her sentence was complete she saw, unmistakably
again, that his eyes accepted and acquiesced in her conclusion.
“Quite,” he said in a level voice. “So for the present my father is
consumed with remorse, and is occupying the state-rooms—you’ve never
seen them; gorgeous tapestry and Lincrusta Walton ceilings—till we come
up to town. He is painting away at the series of cartoons.”
Peter poured himself out a second cup of coffee from the tray that had
been left between them half an hour or more before.
“Aunt Joanna!” he said. “You never heard such a plot or saw such a
person. She’s my mother-in-law’s sister, you know. She’s ‘got at’ my father,
there’s no doubt of it, and she’s secured all the cartoons by bribery and
corruption, instead of their being painted for the gallery—the Art Gallery, I
should say—at Howes. Aunt Eleanor—she’s my father-in-law’s brother’s
wife—has secured the sketches for the cartoons. They’ve been to Howes
once, but my father quite dominated them. That was before the crash, so
you may judge how much more, with that added string of tragedy to his
bow, he would dominate them now. They are more priceless than words can
say. There will be a family gathering at Christmas, I understand. Nellie, do
come. We would have such a gorgeous time if you were there. We would sit
quiet and notice and drink in, and then we would sit over the fire together
when Uncle John and Uncle Abe——”
“Uncle Abe?” asked Nellie in an awed voice.
“Yes. Sir Abel Darley, K.B.E., husband to Aunt Joanna. Don’t interrupt.
When Uncle John and Uncle Abe and Aunt Eleanor and Aunt Joanna have
gone, not staggering at all, but ‘full up,’ to bed, we would have such holy
convocations about them.”
Nellie had inferred a little more information about Silvia by this time,
but what occupied her most was not what she was inferring about anybody.
It was quite enough for her to realize that for the duration, anyhow, of the
first act of the play which they had meant to see she was in the old full
enjoyment of Peter again. They had stepped back into the candour and
closeness of their friendship, and though he had not, as she had, confessed
that he was having a holiday, it was transparently clear that this was the
case. But just there the candour was clouded; she guessed that, even as she
was having a holiday from Philip (God bless him), so Peter was having a
holiday from Silvia. Only—here was the difference—he did not or would
not own up to that. Even in the projected scheme of Christmas-hilariousness
at the uncles and aunts, Silvia did not appear as ever so faintly ridiculous, or
as ever so faintly partaking in the midnight merriment. Throughout their
talk Peter had kept her hermetically apart. Once or twice, Nellie
conjectured, he had pointedly enough refrained from introducing her. She
could visualize the rest of them down at Howes, but the part that to Peter
Silvia played was mysteriously shrouded. When you were laughing at
everybody all round, why should you except one person from the
compliment of amused criticism? It was clear that Silvia had no applause
for the comedy of Peter’s parents, for he had so cordially welcomed her—
Nellie’s—appreciation of it. What, then, was Silvia’s line, what was her
relation, above all, to Peter?
She decided not to burn all her boats, but to set fire to just a little one.
“Won’t Silvia enjoy them too?” she asked.
“Can’t tell,” said Peter.
If there was a lapse of loyalty there, if, in a minor degree, there was a
sense conveyed of disappointment, though of accepting that disappointment
without comment, Nellie decided that Peter was not intending to enlarge on
it. She still (after that small burned boat) clung to the chance of Peter’s
volunteering information, but clearly she would not get that just now; and
another heavy booming of quarters from the clock gave her an excellent
opportunity of abandoning that which, after all, had never been a discussion
on her own initiative.
“Good gracious, it’s a quarter to nine,” she said. “You wretch, Peter!
We’ve missed one act, if not two.”
“Let’s miss them all,” he said, “and have an evening.”
That made her pause, but only for a moment. Peter had consistently
shied away from that one topic she wanted to hear about, and a break of
some sort was much more likely to produce in him the pressure that would
eventually “go pop” than if they remained just sizzling here.
“But we absolutely must go,” she said. “Philip will ask me about the
play, and I couldn’t tell him that you and I simply sat talking till it was
over.”
“Why not?” said Peter.
“Because it isn’t done. My dear, you and I have signed on to the
conventionalities of life. Come along. A bore, but there it is. Besides, how
would you account for your evening to Silvia? Dining at seven, you know.
That requires a theatrical explanation.”
“Oh, don’t be vulgar,” said Peter. “As if Silvia wouldn’t delight in my
spending an evening with you.”
“I know that,” said she. “Don’t lose your sense of humour, Peter. It was a
mild kind of joke.”
“Come on, then,” he said. “And as for its being my fault that we’re so
late——”
The second act was drawing to an end when they stole into their box. On
the stage there was proceeding the most elementary of muddles, to which it
was not in the least worth while to devote any ingenuity. It was clear at the
first glance that these people who pretended to be servants were really
landed gentry, and that just before the end the Earl (who had taken the
house) would propose to the cook and be violently accepted.
Psychologically they presented no point of interest. Far more engrossing to
Nellie was the fact that she had got Peter with her, and the pleasure of that
and the general problem it propounded was far more absorbing. Marriage
had certainly quickened her emotional perceptions, and she inferred, from
the extraordinary delight that it was to be with him again, how much in the
interval she had missed him. She had no reason to complain, either, of the
welcome he had given her, but it was manifest (how she could not definitely
have said) that the quality of that was different from hers to him. To his
sense, as he had openly stated, they had taken up the old attitude, the old
intimacy, without break, but as she thought over that in the few minutes that
elapsed before the act was finished, she found that, for her part, she did not
altogether endorse his view. Certainly the old intimacy was there, firm and
unshaken, but somehow, hovering over it, like a mist which to her eyes
seemed to be luminous with tears, there was some new atmospheric
condition, sunny and tremulous.
Peter turned to her as the house sprang into light again.
“Oh, what a waste of time,” he said. “We should have done much better
to have left our elbows on the table. We’re always doing it too. Do you
remember the last play at which we met? That time you were with Philip
and I with Silvia and Mrs. Wardour. Then we had our talk afterwards; to-
night we had it first. I like the other plan best.”
Though Peter had here stated several things with which she was in
cordial agreement, his tone was not in tune with the old footing, the old
intimacy. Not many minutes ago it had been she who, in opposition to his
inclination, had insisted on breaking their tête-à-tête; now, with all possible
lightness of touch, she suggested its resumption.
“I’ve seen enough,” she said. “I can tell Philip all about it. Let’s go back,
my dear, and have half an hour’s more talk. It was my fault that we broke
up; but how could I have told that the play would have been as silly as this?
Welcome to our website – the perfect destination for book lovers and
knowledge seekers. We believe that every book holds a new world,
offering opportunities for learning, discovery, and personal growth.
That’s why we are dedicated to bringing you a diverse collection of
books, ranging from classic literature and specialized publications to
self-development guides and children's books.
More than just a book-buying platform, we strive to be a bridge
connecting you with timeless cultural and intellectual values. With an
elegant, user-friendly interface and a smart search system, you can
quickly find the books that best suit your interests. Additionally,
our special promotions and home delivery services help you save time
and fully enjoy the joy of reading.
Join us on a journey of knowledge exploration, passion nurturing, and
personal growth every day!
ebookbell.com

More Related Content

Similar to Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson (20)

Vb.net class notes
Vb.net class notesVb.net class notes
Vb.net class notes
priyadharshini murugan
 
ASPNET for PHP Developers
ASPNET for PHP DevelopersASPNET for PHP Developers
ASPNET for PHP Developers
Wes Yanaga
 
Vb & asp .net
Vb & asp .netVb & asp .net
Vb & asp .net
Lakhmichand institute of technology
 
Microsoft SQL Server - SQL Server + Visual Studio Presentation
Microsoft SQL Server - SQL Server + Visual Studio PresentationMicrosoft SQL Server - SQL Server + Visual Studio Presentation
Microsoft SQL Server - SQL Server + Visual Studio Presentation
Microsoft Private Cloud
 
Advanced Programming Using Visual Basic. NET
Advanced Programming Using Visual Basic. NETAdvanced Programming Using Visual Basic. NET
Advanced Programming Using Visual Basic. NET
Tony Lisko
 
Visual Studio 2008 & .Net 3.5
Visual Studio 2008 & .Net 3.5Visual Studio 2008 & .Net 3.5
Visual Studio 2008 & .Net 3.5
Hadi Karimi
 
Foundry Management System Desktop Application
Foundry Management System Desktop Application Foundry Management System Desktop Application
Foundry Management System Desktop Application
Dharmendra Sid
 
Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...
Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...
Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...
ambahoraci
 
235042632 super-shop-ee
235042632 super-shop-ee235042632 super-shop-ee
235042632 super-shop-ee
homeworkping3
 
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
Nancy Thomas
 
ASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh BhasinASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh Bhasin
tevdtridev
 
Chapter 01
Chapter 01Chapter 01
Chapter 01
llmeade
 
ASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh BhasinASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh Bhasin
resulljuz
 
.NET presentation
.NET presentation.NET presentation
.NET presentation
Himanshu Bhalla
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
Synapseindiappsdevelopment
 
Cursos sql server .net visual basic octubre 2010
Cursos sql server .net visual basic octubre 2010 Cursos sql server .net visual basic octubre 2010
Cursos sql server .net visual basic octubre 2010
Servicios Educativos Softrain C.A.
 
Building Applications for SQL Server 2008
Building Applications for SQL Server 2008Building Applications for SQL Server 2008
Building Applications for SQL Server 2008
Dave Bost
 
VSTO
VSTOVSTO
VSTO
Pham Quang
 
Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming
francopw
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
webhostingguy
 
ASPNET for PHP Developers
ASPNET for PHP DevelopersASPNET for PHP Developers
ASPNET for PHP Developers
Wes Yanaga
 
Microsoft SQL Server - SQL Server + Visual Studio Presentation
Microsoft SQL Server - SQL Server + Visual Studio PresentationMicrosoft SQL Server - SQL Server + Visual Studio Presentation
Microsoft SQL Server - SQL Server + Visual Studio Presentation
Microsoft Private Cloud
 
Advanced Programming Using Visual Basic. NET
Advanced Programming Using Visual Basic. NETAdvanced Programming Using Visual Basic. NET
Advanced Programming Using Visual Basic. NET
Tony Lisko
 
Visual Studio 2008 & .Net 3.5
Visual Studio 2008 & .Net 3.5Visual Studio 2008 & .Net 3.5
Visual Studio 2008 & .Net 3.5
Hadi Karimi
 
Foundry Management System Desktop Application
Foundry Management System Desktop Application Foundry Management System Desktop Application
Foundry Management System Desktop Application
Dharmendra Sid
 
Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...
Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...
Developer s Guide to Microsoft Enterprise Library Visual Basic Edition Patter...
ambahoraci
 
235042632 super-shop-ee
235042632 super-shop-ee235042632 super-shop-ee
235042632 super-shop-ee
homeworkping3
 
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl....net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
.net training | learn .net | Microsoft dot net Course | Microsoft dot net onl...
Nancy Thomas
 
ASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh BhasinASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh Bhasin
tevdtridev
 
Chapter 01
Chapter 01Chapter 01
Chapter 01
llmeade
 
ASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh BhasinASP NET Professional Projects 1st Edition Hersh Bhasin
ASP NET Professional Projects 1st Edition Hersh Bhasin
resulljuz
 
Synapseindia dot net development chapter 8 asp dot net
Synapseindia dot net development  chapter 8 asp dot netSynapseindia dot net development  chapter 8 asp dot net
Synapseindia dot net development chapter 8 asp dot net
Synapseindiappsdevelopment
 
Building Applications for SQL Server 2008
Building Applications for SQL Server 2008Building Applications for SQL Server 2008
Building Applications for SQL Server 2008
Dave Bost
 
Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming Chapter 1 — Introduction to Visual Basic 2010 Programming
Chapter 1 — Introduction to Visual Basic 2010 Programming
francopw
 
Introduction to Threading in .Net
Introduction to Threading in .NetIntroduction to Threading in .Net
Introduction to Threading in .Net
webhostingguy
 

Recently uploaded (20)

SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptxSPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Vikas Bansal Himachal Pradesh: A Visionary Transforming Himachal’s Educationa...
Himalayan Group of Professional Institutions (HGPI)
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptxChalukyas of Gujrat, Solanki Dynasty NEP.pptx
Chalukyas of Gujrat, Solanki Dynasty NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptxROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptxBINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptxPEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdfGEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive LearningSustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation SamplerLDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POSHow to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptxRai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Rai dyansty Chach or Brahamn dynasty, History of Dahir History of Sindh NEP.pptx
Dr. Ravi Shankar Arya Mahila P. G. College, Banaras Hindu University, Varanasi, India.
 
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptxSPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
SPENT QUIZ NQL JR FEST 5.0 BY SOURAV.pptx
Sourav Kr Podder
 
Nice Dream.pdf /
Nice Dream.pdf                              /Nice Dream.pdf                              /
Nice Dream.pdf /
ErinUsher3
 
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptxAnalysis of Quantitative Data Parametric and non-parametric tests.pptx
Analysis of Quantitative Data Parametric and non-parametric tests.pptx
Shrutidhara2
 
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Paper 109 | Archetypal Journeys in ‘Interstellar’: Exploring Universal Themes...
Rajdeep Bavaliya
 
The Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdfThe Man In The Back – Exceptional Delaware.pdf
The Man In The Back – Exceptional Delaware.pdf
dennisongomezk
 
Overview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 EmployeesOverview of Off Boarding in Odoo 18 Employees
Overview of Off Boarding in Odoo 18 Employees
Celine George
 
Exploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle SchoolExploring Ocean Floor Features for Middle School
Exploring Ocean Floor Features for Middle School
Marie
 
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptxROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
ROLE PLAY: FIRST AID -CPR & RECOVERY POSITION.pptx
Belicia R.S
 
BINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptxBINARY files CSV files JSON files with example.pptx
BINARY files CSV files JSON files with example.pptx
Ramakrishna Reddy Bijjam
 
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptxPEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
PEST OF WHEAT SORGHUM BAJRA and MINOR MILLETS.pptx
Arshad Shaikh
 
GEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdfGEOGRAPHY-Study Material [ Class 10th] .pdf
GEOGRAPHY-Study Material [ Class 10th] .pdf
SHERAZ AHMAD LONE
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive LearningSustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
LDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation SamplerLDMMIA GRAD Student Check-in Orientation Sampler
LDMMIA GRAD Student Check-in Orientation Sampler
LDM & Mia eStudios
 
june 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptxjune 10 2025 ppt for madden on art science is over.pptx
june 10 2025 ppt for madden on art science is over.pptx
roger malina
 
How to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POSHow to Manage Inventory Movement in Odoo 18 POS
How to Manage Inventory Movement in Odoo 18 POS
Celine George
 
How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18How to Manage Multi Language for Invoice in Odoo 18
How to Manage Multi Language for Invoice in Odoo 18
Celine George
 
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdfABCs of Bookkeeping for Nonprofits TechSoup.pdf
ABCs of Bookkeeping for Nonprofits TechSoup.pdf
TechSoup
 
Ad

Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson

  • 1. Programming Microsoft Sql Server 2000 With Microsoft Visual Basic Net 1st Edition Dobson download https://ebookbell.com/product/programming-microsoft-sql- server-2000-with-microsoft-visual-basic-net-1st-edition- dobson-55141988 Explore and download more ebooks at ebookbell.com
  • 2. Here are some recommended products that we believe you will be interested in. You can click the link to download. Programming Microsoft Sql Server 2000 With Xml Graeme Malcolm https://ebookbell.com/product/programming-microsoft-sql- server-2000-with-xml-graeme-malcolm-926310 Microsoft Sql Server 2000 Programming By Example Carlos Rojas https://ebookbell.com/product/microsoft-sql-server-2000-programming- by-example-carlos-rojas-976716 Programming Microsoft Sql Server 2008 Leonard Lobel Andrew J Brust https://ebookbell.com/product/programming-microsoft-sql- server-2008-leonard-lobel-andrew-j-brust-1232300 Inside Microsoft Sql Server 2008 Tsql Programming Prodeveloper 1st Edition Itzik Bengan https://ebookbell.com/product/inside-microsoft-sql-server-2008-tsql- programming-prodeveloper-1st-edition-itzik-bengan-2112660
  • 3. Beginning Microsoft Sql Server 2008 Programming Robert Vieira https://ebookbell.com/product/beginning-microsoft-sql- server-2008-programming-robert-vieira-5468682 Professional Microsoft Sql Server 2008 Programming Robert Vieira https://ebookbell.com/product/professional-microsoft-sql- server-2008-programming-robert-vieira-5473568 Beginning Microsoft Sql Server 2008 Programming Robert Vieira https://ebookbell.com/product/beginning-microsoft-sql- server-2008-programming-robert-vieira-61013860 Inside Microsoft Sql Server 2005 Tsql Programming Itzik Bengan https://ebookbell.com/product/inside-microsoft-sql-server-2005-tsql- programming-itzik-bengan-917874 Microsoft Sql Server 2005 Programming For Dummies Andrew Watt https://ebookbell.com/product/microsoft-sql-server-2005-programming- for-dummies-andrew-watt-975328
  • 6. Programming Microsoft® SQL Server™ 2000 with Microsoft Visual Basic® .NET Foreword Acknowledgments Introduction Who’s the Book For? What’s Special About This Book? How’s the Book Organized? System Requirem ents Sample Files Support 1. Getting Started with Visual Basic .NET for SQL Server 2000 Visual Studio .NET, the Visual Basic .NET IDE An Overview of ADO.NET Capabilities A Starter ADO.NET Sam ple Using Query Analyzer 2. Tables and Data Types Chapter Resources Data Types for Tables Scripting Tables 3. Program m ing Data Access with T-SQL I ntroduction to Data Access with T-SQL Aggregating and Grouping Rows Processing Dates Joins and Subqueries 4. Program m ing Views and Stored Procedures I ntroduction to Views Creating and Using Views Views for Remote and Heterogeneous Sources I ntroduction to Stored Procedures Creating and Using Stored Procedures Processing Stored Procedure Outputs I nserting, Updating, and Deleting Rows Programm ing Conditional Result Sets 5. Program m ing User-Defined Functions and Triggers I ntroduction to User-Defined Functions Creating and I nvoking Scalar UDFs Creating and I nvoking Table-Valued UDFs I ntroduction to Triggers Creating and Managing Triggers 6. SQL Server 2000 XML Functionality Overview of XML Support XML Formats and Schemas URL Access to SQL Server Template Access to SQL Server 7. SQL Server 2000 Security
  • 7. Overview of SQL Server Security I ntroduction to Special Security I ssues Samples for Logins and Users Samples for Assigning Perm issions 8. Overview of the .NET Fram ework An I ntroduction to the .NET Fram ework An Overview of ASP.NET XML Web Services 9. Creating Windows Applications Getting Started with Windows Forms Creating and Using Class References I nheriting Classes Programm ing Events Exception Handling for Run-Tim e Errors 10. Programm ing Windows Solutions with ADO.NET An Overview of ADO.NET Objects Making Connections Working with Command and DataReader Objects DataAdapters , Data Sets, Forms, and Form Controls Modifying, Inserting, and Deleting Rows 11. Programm ing ASP.NET Solutions Review of ASP.NET Design I ssues Creating and Running ASP.NET Solutions Session State Management Data on Web Pages Validating the Data on a Web Page 12. Managing XML with Visual Basic .NET SQL Server Web Releases Overview of XML Technologies Generating XML Documents with the .NET Framework Dynam ically Setting an XML Result Set The I nterplay Between XML and Data Sets Creating HTML Pages with XSLT 13. Creating Solutions with XML Web Services Overview of Web services A Web Service to Return a Com puted Result A Web Service to Return Values from Tables The SQL Server 2000 Web Services Toolkit More on Populating Controls with Web Services About the Author
  • 8. Forew ord During m y five years at Microsoft, I ’ve been helping developers understand technologies such as Microsoft Visual Studio, Microsoft SQL Server, and Microsoft Office Developer. During the past two years, I have worked on the Microsoft Office XP Visual Basic Language Reference, and now, the MSDN Office Developer Center. I n the m onthly column on MSDN, Office Talk, I have written articles to help Office developers understand the .NET platform and how it affects their current and future development efforts. As I write this foreword to Rick Dobson’s book on programm ing Microsoft SQL Server solutions with Microsoft Visual Basic .NET, I think back to my own experiences developing software applications with Visual Basic. My first experience with Visual Basic was learning the language using version 3.0. I rem ember picking up m y first Visual Basic beginner’s book and being excited as I developed my first few “Hello, World” applications. I couldn’t believe how quick and easy it was to develop software applications that operated sim ilarly to other popular shareware program s of that tim e. However, during that time I also discovered som e of the shortcom ings of Visual Basic as an enterprise-level development language. It was then that I turned my attention to C+ + . I rem ember being very frustrated at trying to learn the language, trying to understand concepts such as pointers, m em ory allocation, and true object-oriented programm ing. I took classes on C+ + at the local university, but I got even m ore frustrated having to wait m onths until I was taught how to create the sim plest Microsoft Windows form, something I did in just a couple of m inutes using Visual Basic. I n my frustration, I gave up trying to learn C+ + and have been using Visual Basic to develop software applications ever since. As each new version of Visual Basic was released, I readied myself to learn new software developm ent technologies. First it was ActiveX control development. Then it was calling the Windows API . Next it was DHTML Applications. Then it was database developm ent using Microsoft SQL Server. I t always seem ed as though I had to learn a new language and a new developm ent paradigm for every new technology that came along. I kept thinking that there had to be an easier and more unified approach. Well, now we’ve reached the advent of the Microsoft .NET platform , and with it, a revolution in the Visual Basic language, Microsoft Visual Basic .NET. I believe that Visual Basic .NET will provide software developers with new opportunities for quickly and easily designing integrated software applications that connect businesses and individuals anytime, anywhere, and on virtually any software device. With advances in the Visual Basic .NET language, Visual Basic .NET developers will finally be on a par with their C+ + and C# counterparts, participating in many high-end developm ent projects. With Visual Studio .NET features such as cross-language debugging, along with Visual Basic .NET conformance to the com mon type system and the com mon language runtime, organizations can drive down their development costs by tapping into the wide range of skills that Visual Basic .NET developers now possess. True object-oriented programm ing is now available in Visual Basic .NET, including features such as inheritance and m ethod overloading. I t’s now simpler to call the Windows API by using the .NET Fram ework Class Libraries. Web application developm ent is now as easy as developing Windows form s–based applications. Database application developm ent is made easier by uniting disparate data object libraries such as DAO, RDO, OLE DB, and ADO under ADO.NET, utilizing the power of XML to consume and transm it relational data over com puter networks. And a new technology, XML Web services, allows Visual Basic .NET developers to host their software applications’ logic over the Web. Additionally, a big issue for
  • 9. software developers today is that of software application deploym ent and versioning. I f you don’t agree, just ask any software developer about “DLL hell,” and you’re bound to get an earful. For m any .NET applications, the .NET platform features “copy and paste” or XCOPY deploym ent. (Users simply copy your application files from the source media to any single directory and run the application.) And because .NET no longer relies on the registry, virtually all DLL compatibility issues go away. With this book, Rick aim s to give you the skills you need to program SQL Server solutions with Visual Basic .NET. I know you will find Rick’s book helpful. Rick brings his experience to bear from three previous books: Programm ing Microsoft Access Version 2002 (Microsoft Press, 2001), Program m ing Microsoft Access 2000 (Microsoft Press, 1999), and Professional SQL Server Development with Access 2000 (Wrox Press I nc., 2000). Rick also brings his experience of leading a successful nationwide sem inar tour. More important, I know you will enjoy Rick’s book because of his deep interest in Visual Basic .NET and SQL Server, and in helping you, the professional developer, understand and apply these technologies in your daily software application developm ent projects. Paul Cornell MSDN Office Developer Center http: / / msdn.m icrosoft.com/ officeMicrosoft Corporation February 2002
  • 10. Acknow ledgm ents This section offers me a chance to say thank you to all who helped make this book possible. I wish to offer special recognition to five support resources. First, the folks at Microsoft Press have been fantastic. Dave Clark, an acquisitions editor, selected me to write the book just months after I completed another book for Microsoft Press. Dick Brown, m y project editor, staunchly stood up for his perception of how to m ake the book’s organization and content clear to you without being petty or boring to m e. Dick also lightened my load substantially by showing a real knack for editing my text without distorting the original intent. When Dick was especially busy, he handed off some of his load to Jean Ross, who also did an adm irable job. Others at Microsoft Press who contributed to my well- being in one way or another include Aaron Lavin and Anne Hamilton. Second, I had excellent working relations with several professionals within Microsoft. Paul Cornell, a widely known technical editor at Microsoft, was kind enough to share his insights on how to present .NET concepts compellingly. I want to thank Paul especially for writing the Foreword to this book. Karthik Ravindran served as the MSXML Beta Product Lead Engineer at Microsoft Product Support Services during the time that I wrote this book. He provided valuable technical content about the SQL Server 2000 Web releases. Other Microsoft representatives providing moral and technical support for this book include Richard Waym ire and Jan Shanahan. Third, I want to express m y appreciation to the many readers, sem inar attendees, and site visitors who took the time to tell m e what I did right or wrong for them, and also to those who shared their technical support questions with me. It is through this kind of feedback that I am able to know what’s important to practicing developers. I encourage you to visit my m ain Web site (http: / / www.programm ingmsaccess.com) and sign the guest book. The entry form includes space for you to leave your evaluation of this book or your question about a topic covered in the book. I prom ise to do my best to reply personally. I n any event, I definitely read all m essages and use them so that I can serve you better with future editions of this, and other, books. Fourth, I want to tell the world how grateful I am to my wife, Virginia. Without Virginia’s warm support, love, and care, this book would be less professional. She relieves m e of nearly every responsibility around the house when I undertake a book project. In addition, she offers strategic advice on the issues to address and their style of coverage. When I run out of tim e, she even pitches in with the proofreading. Fifth, it is important for me to give praise and glory to my Lord and Savior, Jesus Christ, who I believe gave m e the strength and wisdom to write this book. I n addition, He gave m e health during the long gestation period that resulted in the birth of this book. I t is my prayer that the book prove to be a blessing to you.
  • 11. I ntroduction Anyone who buys a book—or considers buying it—wants to know who the book is for, what sets it apart from others like it, and how the book is organized. This introduction covers those three questions, and it also discusses system requirem ents, sample files, and support. • First, w ho is the book for? There are at least two answers to this question. One answer is that the book targets professional developers (and others aspiring to be professional developers). The second group the book addresses is those who want to build full-featured, secure SQL Server solutions with Visual Basic .NET. • Second, w hat’s special about the book? I hope you com e to believe that the m ost important answer to this question is that the book considered quality and depth of coverage more important than rushing to market. The book will arrive on bookshelves m ore than three months after the official release of the .NET Framework. I t is my wish that you derive value from the extra time taken to develop the m any code samples and the in-depth discussions of advanced topics, such as class inheritance, ASP.NET, and XML Web services. • Third, how is the book organized? The short answer is that there are two main sections. One section introduces SQL Server concepts as it dem onstrates T-SQL (Transact SQL) programming techniques. After conveying SQL Server basic building blocks in the first part, the second part reveals how to put those parts together with Visual Basic .NET and related technologies into SQL Server solutions for handling common database chores. The three support item s include a brief description of the book’s companion CD and how to use it, Microsoft Press Support I nformation for this book, and a summary of system and software requirem ents for the sample code presented in the book. W ho’s the Book For? This book targets professional Visual Basic and Visual Basic for Applications developers. From my seminar tours and Web sites (http: / / www.programm ingmsaccess.com and http: / / www.cabinc.net), I know that these professionals are driven by a passion to deliver solutions to their clients through applying the m ost innovative technologies their clients will accept. In-house developers are the go-to persons for getting results fast— particularly for custom in-house systems and databases. I ndependent developers specialize in serving niche situations that can include under-served business needs and work overflows. I n both cases, these professionals need training m aterials that address practical business requirem ents while showcasing innovative technologies without wasting their tim e. This book strives to serve this broad need in two specific areas. This book is for developers looking for code samples and step-by-step instructions for building SQL Server 2000 solutions with Visual Basic .NET. The book focuses on the integration of SQL Server 2000 with .NET technologies tapped via Visual Basic .NET. I t is my firm belief that you cannot create great SQL Server solutions in any programm ing language without knowing SQL Server. Therefore, this book
  • 12. goes beyond traditional coverage of SQL Server for Visual Basic developers. You’ll learn T-SQL program m ing techniques for data access, data manipulation, and data definition. A whole chapter equips you to secure your SQL Server solutions. In addition, there’s plenty of content in this book on Visual Basic .NET and related technologies, such as ADO.NET, ASP.NET, XML (Extensible Markup Language), and XML Web services. The presentation of these technologies demonstrates coding techniques and explores concepts that equip you to build better solutions with SQL Server 2000 databases. I n addition, the book highlights innovations introduced through the Web releases for SQL Server 2000 that integrate SQL Server 2000 tightly with Visual Basic .NET. This isn’t a book about XML, but three of the book’s 13 chapters focus in whole or in part on XML. Therefore, those seeking practical dem onstrations of how to use XML with SQL Server and Visual Basic .NET will derive value from this book. I f you have looked at any of the computer magazines over the past couple of years, you know that XML is coming to a solution near you. However, the rapid pace of XML innovation m ay have dissuaded som e from jum ping on the bandwagon while they wait to see what’s going to last and what’s just a fad. I n the book’s three chapters on XML technology, you’ll learn about XML documents, fragm ents, and formatting as well as related technologies, such as XPath (XML Path Language) queries, XSLT (Extensible Stylesheet Language Transformation), and WSDL (Web Services Description Language). W hat’s Special About This Book? There are several features that make this book stand apart from the flood of books on .NET. One of the m ost important of these is that this book didn’t rush to market but rather shipped m onths after the release of the .NET Framework. This allowed me enough tim e to filter, exam ine, and uncover what were the m ost useful and innovative features for Visual Basic .NET developers building SQL Server solutions. For example, the book includes a whole chapter on creating solutions with XML Web services. That chapter includes two major sections on the SQL Server 2000 Web Services Toolkit, which didn’t ship until the day of the .NET Framework release. The .NET Framework content is at a professional level, but it isn’t just for techies. This book doesn’t assume any prior knowledge of the .NET Framework. I t does assume that you get paid for building solutions programmatically and that at least some of those solutions are for SQL Server databases. Therefore, the book explains basic .NET concepts and dem onstrates how to achieve practical results with those concepts through a huge collection of .NET code samples. This book is about building solutions for SQL Server 2000. I include coverage of the many special features that tie Visual Basic .NET and SQL Server 2000 closely to one another. Although there is coverage of general .NET database techniques, this book dives deeply into T-SQL programm ing techniques so that you can create your own custom database objects, such as tables, stored procedures, views, triggers, and user-defined functions. I n addition, there is separate coverage of the XML features released with SQL Server 2000 as well as separate coverage of the XML features in the first three Web releases that shipped for SQL Server 2000. There are num erous code samples throughout the book. These will equip you to build solutions with Visual Basic .NET, T-SQL, and combinations of the two. Finally, this book is special because of the unique experiences of its author, Rick Dobson. I have trained professional developers in Australia, England, Canada, and throughout the United States. This is my fourth book in four years, and you can find my articles in popular publications and Web sites, such as SQL Server Magazine and MSDN Online. As a Webmaster, my main site
  • 13. (http: / / www.programm ingmsaccess.com) serves hundreds of thousands of sessions to developers each year. I constantly exam ine their viewing habits at the site to determ ine what interests them. I n addition, my site features scores of answers to technical support questions subm itted by professional developers. My goal in offering answers to these questions is to stay in touch with practicing developers worldwide so that my new books address the needs of practicing, professional developers. How ’s the Book Organized? There are two main parts to this book tied together by an introductory part. Part II , the first main part, dwells on SQL Server techniques. Part I II builds on the SQL Server background as it lays a firm foundation in .NET techniques for Visual Basic .NET developers. Part I, the introductory part, demonstrates ways to use SQL Server and Visual Basic .NET together. Part I , I ntroduction Part I , which includes only Chapter 1, has three main goals. First, it acquaints you with the basics of Visual Basic .NET within Visual Studio .NET. You can think of Visual Basic .NET as a major upgrade to the Visual Basic 5 or 6 that you are probably using currently. This first section introduces some concepts that you will find useful as you initially learn the landscape of Visual Basic .NET. The second goal of Chapter 1 is to introduce ADO.NET. I f you think of Visual Basic .NET as a major upgrade to Visual Basic 6, ADO.NET is m ore like a major overhaul of ADO. In two sections, you get an introduction to ADO.NET classes— particularly as they relate to SQL Server— and you get a chance to see a couple of beginner sam ples of how to create SQL Server solutions with Visual Basic .NET and ADO.NET. The third goal of the introductory part is to expose you to Query Analyzer. This is a SQL Server client tool that ships with all comm ercial editions of SQL Server 2000. You can think of it as an IDE for T-SQL code. Most of the book’s first part relies heavily on T-SQL, and therefore having a convenient environment for debugging and running T-SQL code is helpful. The final section of Chapter 1 addresses this goal. Part I I , SQL Server Part I I consists of six relatively short chapters that focus substantially on programm ing SQL Server 2000 with T-SQL. Chapter 2 and Chapter 3 introduce T- SQL and SQL Server data types. I f you are going to program SQL Server and create efficient, fast solutions, you m ust learn SQL Server data types, which is one of the main points conveyed by Chapter 2. Many readers will gravitate to Chapter 3 because it introduces core T-SQL program m ing techniques for data access. You’ll apply the techniques covered in this chapter often as you select subsets of rows and colum ns in data sources, group and aggregate rows from a table, process dates, and join data from two or more tables. Chapter 3 also considers special data access topics, such as outer joins, self joins and subqueries. The next pair of chapters in Part I I , Chapter 4 and Chapter 5, take a look at programm ing database objects that you will use for data access and data manipulation, such as views, stored procedures, user-defined functions, and triggers. These database objects are im portant for many reasons, but one of the most important is that they bundle T-SQL statements for their easy reuse. I t is
  • 14. widely known that the best code is the code that you don’t have to write. However, if you do have to write code, you should definitely write it just onc, and then reuse it whenever you need its functionality. Stored procedures are particularly desirable database objects because they save compiled T-SQL statements that can deliver significant speed advantages over resubm itting the same T-SQL statement for compilation each tim e you want to perform a data access or data manipulation task. Chapter 4 and Chapter 5 are also important because they convey T-SQL syntax for using parameters and conditional logic that support dynam ic run-tim e behavior and user interactivity. One of the m ost important features of SQL Server 2000 is its XML functionality. Because XML as a topic is changing so rapidly, Microsoft adopted a strategy of upgrading the SQL Server 2000 XML functionality through Web releases. Although those with SQL Server 2000 can download the Web releases without charge from the Microsoft Web site, the Web releases are fully supported. Chapter 6 introduces core XML functionality introduced with SQL Server 2000 as well as functionality from the first two Web releases. I n particular, you can learn in this chapter about I IS virtual directories as well as form ats for XML docum ents and schemas. You also learn about templates in virtual directories that facilitate data access and data manipulation tasks over the Web. Chapter 7 closes out the SQL Server part of the book with an in-depth look at programm ing SQL Server security. I n these tim es, security has grown into a monum ental topic, and this chapter can keep you out of trouble by blocking hackers from getting into or corrupting your database. You learn such topics as how to create and manage different types of login and user accounts and how to control the perm issions available to individual accounts as well as groups of accounts. By learning how to script accounts and perm issions with T-SQL, you simplify revising and updating security as conditions change (for exam ple, when users leave the company or when new, sensitive data gets added to a table). Part I I I , .NET Chapter 8 starts the .NET part of the book with a review of selected .NET topics that are covered in the initial look Chapter 1 offered at the .NET Fram ework. This chapter provides an overview of the architecture for .NET solutions, and it drills down on two topics: ASP.NET and XML Web services. The general purpose of this chapter is the same as Chapter 1, which is to introduce concepts. The emphasis in Chapter 8 isn’t how you do som ething, but rather what are the major technologies enabling you to do som ething. Chapter 1 and Chapter 8 are both relatively short chapters, but you may find them invaluable if you are the kind of person who benefits from high-level overviews of a collection of topics. Chapter 9 starts with a close exam ination of how to use Windows Form s with Visual Basic .NET. I t then shifts its focus to a review of traditional class processing concepts via Visual Basic .NET as an introduction to class inheritance, a new object-oriented feature that makes its first appearance in Visual Basic with Visual Basic .NET. Next the treatm ent of classes progresses to the handling of built-in events as well as the raising of custom events. Finally the chapter closes with an exam ination of the new exception handling techniques for processing run- time errors. Chapter 10 is a how-to guide for solutions to typical problems with ADO.NET. Before launching into its progression of sam ples showing how to perform all kinds of tasks, the chapter starts with an overview of the ADO.NET object m odel that covers the main objects along with selected properties and m ethods for each object. The how-to guide focuses on data access tasks, such as selecting rows and columns from SQL Server database objects, as well as data manipulation tasks, such as inserting, updating, and deleting rows in a table. Working through
  • 15. the samples in the how-to guide offers a hands-on feel for using the System .Data.SqlClient namespace elem ents to perform typical tasks. Chapter 11 switches the focus to the Web by addressing the creation and use of ASP.NET solutions. This chapter starts by introducing basic elem ents that you need to know in order to use ASP.NET to create great Web solutions with Visual Basic .NET. These include learning what happens as a page does a round-trip from a browser to a Web server and back to the browser— particularly for data associated with the page. Other prelim inary topics that equip you for building professional Web solutions include running the same page in m ultiple browser types and sniffing the browser for cases in which you want to send a page optim ized for a specific kind of browser type. Managem ent of session state is a major topic in the chapter, and you learn how to use enhancem ents to Session variables for Web farms as well as the new view state variables, a non-server- based technique for managing state in ASP.NET solutions. The last two sections in the chapter deal with ADO.NET topics in ASP.NET solutions and the new autom atic data validation features built right into ASP.NET. The last two chapters in the book explore how XML interplays with Visual Studio .NET and SQL Server 2000. For example, Chapter 12 exam ines special tools in Visual Studio .NET to facilitate the design and editing of XML docum ents and schemas. I n addition, you learn how to designate XPath queries that accept run- time input for returning SQL Server result sets inside Visual Basic .NET programs. The chapter dem onstrates techniques for processing the XML document associated with all ADO.NET data set objects. I n the chapter’s last section, I present a couple of code sam ples that illustrate how to program static HTML pages based on XML documents with XSLT. Chapter 13 drills down on XML Web services by dem onstrating several different approaches for creating Web services as well as consum ing XML output from Web services. Web services behave somewhat like COM objects in that you can set up server applications for client applications. The server applications expose m ethods to which the client applications can pass param eters. XML comes into play with Web services in a couple of areas. First, Web services represent their inputs and outputs via WSDL, an XML-based language that form ally describes an XML Web service. Second, Web services return data to their clients as XML documents or document fragm ents. System Requirem ents The requirem ents for this book vary by chapter. I developed and tested all samples throughout this book on a com puter equipped with Windows 2000 Server, SQL Server Enterprise Edition, and the Enterprise Developer Edition of Visual Studio .NET, which includes Visual Basic .NET. To use this book, you’ll need to have Visual Basic .NET or Visual Studio .NET installed on your computer. (See Chapter 1 for m ore information on versions of Visual Basic .NET and Visual Studio .NET.) I n addition, you’ll need SQL Server 2000, and for som e of the chapters, you’ll need SQL Server 2000 updated with Web releases 1, 2, and 3. Chapter 6 gives the URLs for downloading Web releases 1 and 2. Chapter 12 gives two different URLs for downloading Web Release 3— one with the SQL Server 2000 Web Services Toolkit and the other without it. For selected chapters, you can run the samples with less software or different operating systems than the one that I used. For example, chapters 2 through 5 will run on any operating system that supports a comm ercial version of SQL Server 2000, such as Windows 98 or a m ore recent Windows operating system. Chapter 7 requires an operating system that supports Windows NT security, such as Windows 2000 or Windows XP Professional. Chapter 6, Chapter 11, and
  • 16. Chapter 13 require Microsoft I nternet Inform ation Services (I I S). I n addition, Chapter 6 requires the installation of Web releases 1 and 2. For Chapter 11, your system needs to m eet the m inim um requirem ents for ASP.NET. (See a note in the “How Does ASP.NET Relate to ASP?” section of Chapter 8.) Several of the samples in Chapter 1 3 require Web Release 3 and its associated SQL Server 2000 Web Services Toolkit. Sam ple Files Sample files for this book can be found at the Microsoft Press Web site, at http: / / www.m icrosoft.com/ m spress/ books/ 5792.asp. Clicking the Com panion Content link takes you to a page from which you can download the sam ples. Supplem ental content files for this book can also be found on the book’s companion CD. To access those files, insert the companion CD into your computer’s CD-ROM drive and make a selection from the menu that appears. I f the AutoRun feature isn’t enabled on your system (if a m enu doesn’t appear when you insert the disc in your computer’s CD-ROM drive), run StartCD.exe in the root folder of the com panion CD. I nstalling the sam ple files on your hard disk requires approximately 15.3 MB of disk space. I f you have trouble running any of these files, refer to the text in the book that describes these programs. Aside from the sample files that this book discusses, the book’s supplem ental content includes a stand-alone eBook installation that will allow you to access an electronic version of the print book directly from your desktop. Support Every effort has been m ade to ensure the accuracy of this book and the contents of the companion CD. Microsoft Press provides corrections for books through the World Wide Web at the following address: http: / / www.m icrosoft.com/ m spress/ support To connect directly to the Microsoft Press Knowledge Base and enter a query regarding a question or an issue that you may have, go to: http: / / www.m icrosoft.com/ m spress/ support/ search.asp If you have comments, questions, or ideas regarding this book or the companion content, or questions that are not answered by querying the Knowledge Base, please send them to Microsoft Press via e-mail to: mspinput@m icrosoft.com Or via postal mail to: Microsoft Press Attn: Programm ing Microsoft SQL Server 2000 with Microsoft Visual Basic .NET Editor One Microsoft Way Redm ond, WA 98052-6399 Please note that product support is not offered through the above mail address. For product support information, please visit the Microsoft Support Web site at: http: / / support.m icrosoft.com
  • 17. Chapter 1. Getting Started w ith Visual Basic .NET for SQL Server 2 00 0 This book aims to give professional developers the background that they need to program SQL Server applications with Microsoft Visual Basic .NET. This overall goal implies three guidelines: • First, the book targets practicing developers. I n my experience, these are busy professionals who need the details fast. These individuals already know how to build applications. They buy a book to learn how to build those applications with a specific set of tools. • Second, the book is about building applications for SQL Server 2000. This focus justifies in-depth coverage of SQL Server program m ing topics— in particular, T-SQL, Microsoft’s extension of the Structured Query Language (SQL). • Third, the book illustrates how to program in Visual Basic .NET, but with particular emphasis on database issues for SQL Server 2000. Special attention goes to related .NET technologies, such as the .NET Fram ework, ADO.NET, ASP.NET, and XML Web services. My goal in this chapter is to equip you conceptually for the rest of the book. Therefore, this chapter includes material that acquaints you with application developm ent techniques and topics for SQL Server 2000 and Visual Basic .NET. The discussion of the samples in this chapter generally aim s to convey broad approaches instead of how to run the sample. All the remaining chapters except for Chapter 8, another conceptual chapter, have sam ples with instructions aim ed at professional developers. I believe that the overwhelm ing majority of professional Visual Basic developers have no hands-on fam iliarity with Visual Basic .NET and its related technologies. If you already knew Visual Basic .NET, it wouldn’t make any sense to buy a book describing how to use it. This chapter therefore focuses on how to get started with Visual Basic .NET and one of its core related technologies for those building SQL Server applications— ADO.NET. I also believe that m ost Visual Basic developers don’t have an intimate knowledge of SQL Server— especially for creating user-defined objects, such as tables, views, and stored procedures. This capability can em power you to build m ore powerful and more secure applications. As you learn about database objects and how to create them in Chapter 2 through Chapter 7, reflect back on the Visual Basic .NET coverage in this chapter and how to marry database creation techniques and Visual Basic .NET developm ent techniques. One of the best tools to build database objects is SQL Server 2000 Query Analyzer. This chapter’s closing section conveys the basics of Query Analyzer that you need to follow the sam ples in Chapter 2 through Chapter 7. Visual Studio .NET, the Visual Basic .NET I DE Visual Studio .NET is the new m ultilanguage integrated developm ent environm ent (I DE) for Visual Basic, C# , C+ + , and JScript developers. I f you are developing solutions for Visual Basic .NET, I definitely recom mend that you use Visual Studio .NET as your developm ent environm ent. This section dem onstrates how to get started using Visual Studio .NET for developing solutions with Visual Basic .NET.
  • 18. Visual Basic .NET is available as part of Visual Studio .NET in four editions: • Professional • Enterprise Developer • Enterprise Architect • Academ ic All four editions of Visual Studio .NET include Visual Basic .NET, Microsoft Visual C# .NET, Microsoft Visual C+ + .NET, and support for other languages. I n addition, Microsoft offers Visual Basic .NET Standard, which doesn’t include Visual C# .NET or Visual C+ + .NET. Because this book targets professional Visual Basic developers creating SQL Server applications, it uses the Enterprise Developer Edition of Visual Studio .NET. You may notice some differences if you’re using another edition. Visual Studio .NET can be installed on computers running one of five operating system s: Windows 2000, Windows NT, Windows XP, Windows ME, and Windows 98. Not all the .NET Framework features are available for each operating system. For example, Windows 98, Windows Me, and Windows NT don’t support developing ASP.NET Web applications or XML Web services applications. The samples for this book are tested on a computer running Windows 2000 Server, which does support all .NET Fram ework features. Starting Visual Studio .NET To open Visual Studio .NET, click the Start button on the Windows taskbar, choose Programs, and then choose Microsoft Visual Studio .NET. Visual Studio displays its integrated developm ent environm ent, including the Start Page (unless you previously configured Visual Studio to open differently). From the Start Page, you can configure Visual Studio to work according to your developm ent preferences, and you can start new solutions as well as open existing projects. Configuring Visual Studio .NET for Visual Basic .NET Use the links on the left side of the Start Page to begin configuring Visual Studio .NET for developing solutions in Visual Basic .NET. Click the My Profile link to open a pane in which you can specify an overall profile as well as individually indicate your preferences for Keyboard Schem e, Window Layout, and Help Filter. You also can designate the initial page that Visual Basic .NET displays. When you are beginning, it m ay be particularly convenient to choose Show Start Page. As a Visual Basic developer who has worked with Visual Basic 6, you m ight feel m ost familiar with a layout that reflects your prior developm ent environm ent. Figure 1- 1 shows these My Profile selections. Figure 1 -1 . My Profile selections for starting Visual Studio .NET for a Visual Basic developer.
  • 19. Using the Start Page After setting your profile, you can return to the initial Start Page pane by choosing the Get Started link from the menu on the left border. I f you had created previous solutions, the last four m odified projects would appear on the Projects tab of the Start Page. The tab shows project nam es along with date last modified. I f a project you want to view doesn’t appear on the list, you can click the Open Project link to display the Open Project dialog box and then navigate to a directory containing the previously created solution. Select the project’s folder that you want to open in the I DE, and double-click the solution file (.sln) for the project. The next section illustrates this process in the context of a sample project. To create a new solution, click the New Project link to open the New Project dialog box. I f you saved preferences such as those shown in Figure 1-1, the dialog will automatically select Visual Basic Projects in the Project Types pane of the New Project dialog box. On the right, you can select a template for launching a project. Table 1-1 shows the project template nam es along with a brief description available from the Enterprise Developer Edition of Visual Studio .NET. Choosing a template (by clicking OK after selecting a template) opens a project ready for creating the type of solution that you want to develop. When Visual Studio .NET saves the tem plate to start a new project, it specifies either a file folder or a Web site for the template’s files; you can override the default nam es for the file folder and Web site.
  • 20. Note Not all the project template types in Table 1-1 are available with the non-Enterprise (or Standard) editions of Visual Studio .NET. In addition to the empty projects, the Standard editions make available the Windows Application, ASP.NET Web Application, ASP.NET Web Service, and Console Application templates. 7DEOH9LVXDO%DVLF1(73URMHFW7HPSODWH7SHV 7HPSODWH1DPH UHDWHV$ Windows Application Windows application with a form Class Library Windows application suitable for a library of classes without a form Windows Control Library Project for developing custom reusable form controls for Windows applications ASP.NET Web Application Web application on a Web server ASP.NET Web Service XML Web service on a Web server Web Control Library Project for developing custom reusable controls for Web applications Console Application Command line application that operates in an MS-DOS–style window (the Console) Windows Service Windows service, form erly NT service, application that runs in the background without its own custom user interface Em pty Project Local project with no custom style Em pty Web Project Web project with no custom style New Project I n Existing Folder Blank project in an existing folder There are two main categories of templates: Web projects and local projects. Web projects perm it a browser to serve as the client for a project. Web projects are optim ized for form processing on the Web server. Local projects offer custom form user interfaces with the capability of processing on a local workstation. Local projects can provide richer environments more conducive to client-side programm ing, but local projects don’t offer the wide accessibility of solutions running from a Web server. Creating and Running a Console Application When you select a Console Application template and click OK to launch a new project, Visual Studio .NET responds by opening a project with a blank module. I n addition to the Module window, Visual Studio displays Solution Explorer and the Properties window. You can enter code directly into the Module window, which appears as a tab that you can select alternately with the Start Page. Figure 1-2 shows a code sam ple in the Main subroutine that prompts for a first and second nam e before com bining them and displaying them in the Console (the computer’s monitor). The code is also available as MyNam eIsFrom Console in the Chapter 1 folder on the companion CD for this book. Although Visual Basic developers didn’t previously have Console applications routinely available, this sample should be
  • 21. very easy to follow. The final two lines present an instruction and cause the window to remain open until the user responds to the instruction. This allows the user to view the full name in the Console window. Figure 1-2. A Console application for displaying a full nam e based on user input for first and second nam es. To the right of the Module window are two other windows. The top one of these is Solution Explorer. I t shows the file structure for the solution. Solution Explorer indicates in its first line that the solution consists of just one project. Below that line appears the name of the project, MyNam eI sFrom Console. Within the project are three entries: one each for the References, AssemblyI nfo.vb, and Module1.vb elem ents within the solution’s project. By default, the Properties window is below Solution Explorer. I n the Full Path property text box is an excerpt showing the path to Module1.vb on my computer. When you click the project name in Solution Explorer, the Project Folder text box in the Properties window displays the path of the directory holding the solution’s files. It is this directory that you copy to deploy your solution on another computer with the .NET Fram ework installed. The solution won’t run without the com mon language runtime on the computer to which you copy the directory containing the .NET Fram ework solution. See Chapter 8 for m ore detailed coverage of the .NET Fram ework, including the runtime and distributing .NET Fram ework solutions as assemblies of files in folders. You can test run the application by choosing Start from the Debug m enu, or by pressing F5. This opens the Console window with a prompt to enter a first nam e. After you close your application and save any changes to it, your solution appears
  • 22. on the Start Page for recent solutions. I f you start Visual Studio .NET and the solution you want to open doesn’t appear on the Projects tab of the Start Page, you can also open the solution by clicking Open Project. I n the Open Project dialog box, choose the file with the .sln extension and the solution’s nam e (MyNam eIsFromConsole). A solution can contain just one .sln file, but it can contain m ultiple projects. You also can run the solution and open the Console window directly from Windows Explorer without using Visual Studio .NET. Open the bin subdirectory within the directory containing the assembly folder for the solution. Then double- click the MyNameIsFrom Console.exe file. This opens the Console window with the prompt for a first nam e. An Overview of ADO.NET Capabilities ADO.NET encapsulates the data access and data manipulation for the .NET Framework. This section gives you an overview of the topic that equips you for a starter sam ple in the next section. Microsoft chose the nam e ADO.NET for the .NET Framework data access com ponent to indicate its association with the earlier ADO technology for data access. While there are som e sim ilarities in syntax between ADO.NET and ADO (particularly for connection strings), many will find the differences are m ore obvious than the sim ilarities. These differences substantially upgrade ADO.NET over ADO in two key areas— scalability and XML (Extensible Markup Language) interoperability. As a result, you will be able to create database applications with ADO.NET that serve m ore users and share m ore data than you did with ADO. See Chapter 10 for a m ore intensive examination of ADO.NET. Chapter 12 explicitly explores interoperability between ADO.NET and XML. .NET Data Provider Types Your .NET Fram ework solutions require .NET data providers to connect to data sources. These providers are different from those used with ADO, but there are distinct similarities in some of the ways you use them. With .NET data providers, your solutions can connect, read, and execute commands against data sources. The .NET providers also offer selected other functions, such as the m anagement of input and output parameters, security, transactions, and database server errors. Visual Studio .NET ships with two .NET data providers— the SQL Server .NET data provider and the OLE DB .NET data provider. In addition, you can download an ODBC .NET data provider from the Microsoft MSDN download site (http: / / msdn.m icrosoft.com/ downloads/ default.asp). Note As I write this chapter, the ODBC .NET data provider just became available with the rollout of the shipping version of Visual Studio .NET. You can download it from http: / / msdn.microsoft.com/ downloads/ default.asp?url= / downloads/ s ample.asp?url= / msdn-files/ 027/ 001/ 668/ msdncompositedoc.xml. The URLs for resources sometimes change. You can always search for the ODBC .NET data provider at the MSDN download site to obtain its current download location.
  • 23. The three providers taken together offer fast, highly focused access to selected data sources as well as general access to a wide range of possible data sources. The SQL Server .NET data provider is optim ized for SQL Server 7.0 and SQL Server 2000. This data provider connects directly to a SQL Server instance. The OLE DB .NET data provider connects to OLE DB data sources through two intermediate layers— the OLE DB Service Component and the classic OLE DB provider introduced along with ADO. The OLE DB Service Component m anages connection pooling and transaction services. The classic OLE DB provider, in turn, directly connects to a database server. Microsoft explicitly tested the OLE DB .NET data provider with SQL Server, Oracle, and Jet 4.0 databases. Use the OLE DB .NET data provider to connect to the SQL Server 6.5 version and earlier ones. This provider is also good for connecting to your Microsoft Access solutions based on the Jet 4.0 engine. The OLE DB .NET data provider definitely doesn’t work with the OLE DB provider for ODBC data sources (MSDASQL). Because the .NET OLE DB data provider doesn’t connect to ODBC data sources, you require the ODBC .NET data provider for connecting to ODBC data sources from your .NET Framework solutions. There are four main .NET data provider classes for interacting with a rem ote data source. The nam es of these classes change slightly for each type of provider, but each .NET data provider has the sam e four kinds of classes. The names for the SQL Server .NET data provider classes for interacting with SQL Server instances are SqlConnection, SqlCommand, SqlDataReader, and SqlDataAdapter. You can use the SqlDataReader class for read-only applications from a SQL Server data source. Two especially convenient ways to display results with a SqlDataReader class are in a m essage box or the Visual Studio .NET Output window. The SqlDataAdapter class acts as a bridge between a remote SQL Server data source and a DataSet class instance inside a Visual Basic .NET solution. A data set in a Visual Studio solution is a fifth type of ADO.NET class. A data set can contain m ultiple tables. A sixth ADO.NET class is the DataView class, which acts like a view based on a table within a DataSet object. Windows Forms in Visual Basic .NET applications can bind only to tables within a DataSet object and DataView objects. I examine the DataSet object later in this section. Chapter 10 includes a systematic summary of all six ADO.NET classes that reviews selected properties and m ethods of each class. The overview of ADO.NET classes in Chapter 10 is supported by num erous code samples that illustrate how to manipulate instances of the classes programmatically. Note In order to use abbreviated names, such as those listed in this section for the SQL Server .NET data provider class instances, your application needs a reference to the SqlClient namespace. You can create such a reference with an Imports System.Data.SqlClient statement just before a Module declaration. SqlConnection Class An instance of the SqlConnection class can interface directly with a SQL Server data source. Use a constructor statement to instantiate a SqlConnection object from the SqlConnection class. The constructor statement is a new type of sy-ntax for .NET Fram ework solutions. This type of statement perm its you to declare, instantiate, and pass startup param eters to an object based on a class. With the SqlConnection constructor statem ent, you can specify a connection string as an argum ent for the constructor statem ent. Alternatively, you can assign the
  • 24. connection string to the SqlConnection object after its instantiation with a property assignm ent statement for the ConnectionString property. The following line shows the syntax to instantiate a new SqlConnection object, MySQLCnn1, with a connection string designating integrated security to the m ydb database on the myserver instance of SQL Server. You don’t have to explicitly indicate a provider because the constructor statem ent reveals the type of provider through its reference to the SqlConnection class. Dim MySQLCnn1 As New _ SqlConnection(“Integrated Security=SSPI; _ Data Source=myserver;Initial Catalog=mydb) After instantiating a SqlConnection object, you need to invoke its Open method before the object can link another object based on one of the other SQL Server .NET data provider classes, such as SqlCommand, SqlDataAdapter, or SqlDataReader, to a SQL Server instance. I nvoke the Close m ethod to recover the resources for a SqlConnection object when your solution no longer needs it. The Close m ethod rolls back any pending transactions and releases the connection to the connection pool. The Dispose m ethod is also available for removing connections, but it invokes the Close m ethod and performs other .NET adm inistrative functions. Microsoft recomm ends the Close m ethod for removing a connection. Unclosed connections aren’t returned to the connection pool. SqlCom m and and SqlDataReader Classes One way to put a connection to use is to employ it along with the SqlCom mand and SqlDataReader objects. A SqlDataReader object can maintain an open forward-only, read-only connection with a SQL Server database. While the SqlDataReader using a SqlConnection object is open, you cannot use the SqlConnection object for any other purpose except to close the connection. Closing a SqlDataReader object releases its associated SqlConnection object for other uses. The SqlDataReader class doesn’t have a constructor statement. You declare the SqlDataReader object with a Dim statement and assign a result set from a SqlCommand object to a SqlDataReader with the ExecuteReader method of the SqlCommand object. Finally, invoke the SqlDataReader object Read method to open a row from the result set in the SqlDataReader. The SqlCommand object can serve multiple functions, including processing a T- SQL statem ent against a connection. When used in this fashion, the SqlCommand can take two argum ents. The first can be a T-SQL data access statement, such as SELECT * FROM MyTable . The second SqlCom m and argum ent designates the source connection for the T-SQL statem ent. For example, you can use the name of a SqlConnection object, such as MySQLCnn1. Figure 1-3 shows the route from a SQL Server data source to a SqlDataReader object. Although the SqlConnection and SqlCom mand objects support two-way interaction with a data source, the SqlDataReader object allows read-only access to the result set from the T-SQL statem ent serving as an argum ent for a SqlCommand constructor. Because a SqlDataReader object cannot specify its own data source, a SqlDataReader object must link to a SqlConnection object through an intermediate SqlCom mand object. Figure 1 -3 . A schem atic illustrating the route by w hich a SqlDataReader object returns values to an application.
  • 25. The SqlCommand object can do more than provide a result set to the SqlDataReader object. The discussion of the SqlDataReader object described the use of the SqlCom mand object ExecuteReader method. Three related methods highlight som e contrasting SqlCom mand object functionality. • Invoke the ExecuteNonQuery m ethod to perform two types of actions. First, use this method to perform data definition tasks, such as creating stored procedures and views. Second, the ExecuteNonQuery m ethod can enable data m anipulation tasks, such as inserts, updates, and deletes. • Next, you can apply the ExecuteScalar m ethod to a SqlCommand object when you want to return a single value from a SELECT statement. The method returns the first colum n from the first row of a result set. I f you program this cell to be an aggregate value such as a count or sum , you can readily extract that single value with the ExecuteScalar method. • Finally, the ExecuteXMLReader m ethod opens a T-SQL source statem ent with a FOR XML clause into an XMLReader object. Chapter 6 contains extensive coverage of the FOR XML clause. Objects for dealing with XML will be covered in Chapter 12. The SqlDataAdapter Class and the DataSet Class You use objects based on the SqlDataAdapter class in combination with objects based on the DataSet class. A DataSet object, which is an instance of the DataSet class, represents an in-memory cache of data retrieved from a database. The DataSet object offers a disconnected data source as opposed to the always- connected data source for SqlDataReader objects. As a consequence, using the SqlDataAdapter and DataSet objects instead of a SqlDataReader object improves application scalability. This scalability improvem ent results because the DataSet doesn’t persist a connection to its underlying data source over the whole of its lifetim e as does the SqlDataReader object. While the SqlDataReader isn’t as scalable as the SqlDataAdapter/ DataSet combination, the SqlDataReader can provide faster performance from a remote data source because it delivers data in the style of a forward-only, read-only cursor— the classic firehose delivery m odel. Note The term firehose refers to the fact that data gushes out of a forward-only, read-only cursor. The SqlDataAdapter and DataSet objects combine to enable both data access and data manipulation capabilities. This is important because SqlDataReader objects provide strictly data access capabilities (that is, you cannot perform update,
  • 26. insert, or delete tasks with a SqlDataReader object). Use the SqlDataAdapter Fill method to populate a DataSet object with values from a SQL Server data source. Because a single DataSet object can work with multiple SqlDataAdapter and OLE DB DataAdapter objects, you can populate a single DataSet object with heterogeneous data sources from m ultiple database servers. For exam ple, you can populate a single data set with tables, views, or stored procedures from two different SQL Server instances or from Access and Oracle data sources in addition to a SQL Server data source. Furtherm ore, you can join all the data sources within a DataSet object on fields with comm on data types. Use the SqlDataAdapter Update m ethod to transfer changes from a DataSet object to its underlying data sources. When users perform insert, update, and delete operations against the contents of a DataSet object, those m odifications don’t transfer to the data sources for the DataSet object until your application invokes the Update m ethod for a SqlDataAdapter object underlying the data source. Despite its nam e, the Update method can process all three types of data manipulation operations. However, you need a custom SqlCommand object to accomm odate each type of data manipulation task. Therefore, a SqlDataAdapter can relate to a remote data source through m ore than a single SqlCom mand object. Between the tim e you populate the DataSet object and the tim e your application invokes the SqlDataAdapter Update method, it’s possible for the underlying data source on a SQL Server instance to change. Any changes can cause exceptions because the original values in a data set can be different from the current values in the SQL Server data source. The SqlDataAdapter has events and properties to help manage exceptions that can occur during an update process. Figure 1-4 presents a schematic diagram summarizing how SqlDataAdapter and DataSet objects exchange data with an underlying data source. By contrasting this diagram with the one in Figure 1-3, you can easily spot an important difference between the SqlDataReader and a DataSet object supplied by a SqlDataAdapter object. The capability of perform ing data manipulation with the DataSet object is a critical feature that m eans many applications will rely on a DataSet object instead of a SqlDataReader object. Figure 1-4. A schem atic illustrating the route by w hich SqlDataAdapter and DataSet objects exchange values w ith a SQL Server data source.
  • 27. The DataSet object offers an object model for m anaging the individual elements within it. The DataSet object consists of a DataTable collection (along with other elem ents). This collection can contain one or more tables. You can create these tables with the SqlDataAdapter Fill m ethod when you initially populate a DataSet object from a SQL Server data source. The SelectCommand property, which is a T-SQL statem ent or a stored procedure, for a SqlDataAdapter object can serve as the basis of a table in the DataTable collection for a DataSet object. You can use multiple SqlDataAdapter objects to add m ore than one table to a DataSet object. Each table has a rich object model that perm its the designation of prim ary keys and foreign keys as well as constraints to manage data integrity within a table. One very practical use for the DataTable collection and the object m odel for individual tables is that you will use it to navigate among the values within a DataSet object. Note In addition to referencing the column values of rows within an individual DataTable in a DataSet object, you can reference the schema of DataTable objects within a DataSet object. This is particularly convenient when you want to create a table that you want to populate with data from an XML document. The DataSet object supports four key m ethods for exchanging its data with XML documents. Two of the methods are used for writing XML docum ents based on a DataSet object, and two are for reading XML docum ents into a DataSet object. Within each pair, one m ethod focuses just on transferring schema information and the other focuses on transferring data as well as schema information. A Starter ADO.NET Sam ple This section presents a starter sample to illustrate som e of the concepts described in the preceding section. Don’t worry about following the details of the example. I nstead, pay attention to how easy it is to get started with ADO.NET. This section reinforces the presentation of basic ADO.NET concepts described in the preceding section with simple drag-and-drop techniques and a little code included to tie objects together or enable selected functionality. See Chapter 10 for a collection of code samples that illustrate how to program ADO.NET objects when you require custom ized solutions not readily available from the graphical developm ent environm ent. Most professional developers get called on to do the hard work that goes beyond dragging and dropping objects. After all, if it were easy, they wouldn’t need you. However, it is nice to start out by seeing how easy it is to create a simple solution mostly by dragging and dropping. Note For those who want the sample from this section as a point of departure, it is available on the book’s CD as the GraphicalDataBind solution. Adding a SqlDataAdapter, SqlConnection, and DataSet
  • 28. You can drag a SqlDataAdapter object to a form just like a text box or a com bo box in Visual Basic 6. There is even a wizard to help you configure the SqlDataAdapter object. Figure 1-5 shows the opening screen imm ediately after dragging a SqlDataAdapter object to the startup blank form, Form 1, for a Windows application. You can use this wizard to specify two ADO.NET objects. Figure 1 -5 . The Data Adapter Configuration W izard enables you to graphically configure a SqlDataAdapter object and its related SqlConnection object for use w ith a W indow s form . First, you can designate a SQL Server database to which to connect; this creates a SqlConnection object. This wizard offers several routes for specifying a database connection. For example, you can pick a previously created connection, or you can create a new collection from the Data Link Properties dialog box. This dialog box lets you specify the comm on connection string argum ents, such as a database server, a type of authentication, and a database nam e. I n this starter sample, I used the default connection to the Northwind database. Second, you can specify a data source within a database connection using a SQL string or a stored procedure. For this starter application, I used SELECT CategoryID, CategoryName FROM Categories as the SQL string source for the SqlDataAdapter object. Although a graphical designer is available for building query statem ents, you will be severely hampered as a SQL Server developer if you don’t learn T-SQL, the dialect of SQL that SQL Server supports. I n addition, you will find a grasp of T-SQL important for crafting the statem ents for the SqlCommand objects that enable you to build solutions that update a SQL Server data source from a Windows application.
  • 29. After you finish configuring the Data Adapter Configuration Wizard, the component tray will open below your blank form. The tray will hold the two objects that the wizard created— a SqlDataAdapter object and a SqlConnection object. Because a SqlDataAdapter object is m erely a bridge between a remote data source and a data set in a Windows application, you will need to create a data set. Then your SqlDataAdapter object can fill the data set with data from the rem ote data source specified by your replies to the Data Adapter Configuration Wizard. Im mediately after a SqlDataAdapter object is created, three links are displayed near the bottom of the Properties window for the object. One of these links reads Generate Dataset. Clicking the link opens the Generate Dataset dialog box, in which you designate an existing data set or specify the name for a new one. Figure 1-6 shows the specification of a new data set nam ed DsCategories for the SqlDataAdapter created with the Data Adapter Configuration Wizard. When you click OK within the Generate Dataset dialog box portrayed in Figure 1-6, Visual Basic .NET adds a new object nam ed DsCategories1 to the tray below the form . In addition, Visual Basic .NET adds an XML schema nam ed DsCategories.xsd to the solution that describes the data set. You can view the schema for the data set graphically or as XML code by double-clicking the file’s name in Solution Explorer. The schema’s graphical view is interactive so that you can change the data type specification for columns and make other design changes to the Categories table. The Properties window for the DsCategories.xsd shows the nam e of the table specification as Categories. At this point, you have completed the creation of the DsCategories data set, which contains a DataTable named Categories. Figure 1-6 . You need to add a data set before you can use a SqlDataAdapter. You can add the data set as sim ply as giving it a nam e in the Generate Dataset dialog box.
  • 30. Note Although the Generate Dataset dialog box shows the data set name as DsCategories, Visual Basic .NET assigns DsCategories1 as the data set name in the tray below Form1. After adding a SqlDataAdapter object and a DataSet object to an application, you can preview the data that the SqlDataAdapter will bring to the application. Clicking the Preview Data link in the Properties window for a SqlDataAdapter object opens the Data Adapter Preview dialog box. Click the Fill DataSet button to display the data in the dialog box. Because of the SQL statem ent used when configuring our SqlDataAdapter object, the button populates the form with a table that shows the CategoryID and CategoryName column values from the Northwind database. Don’t confuse clicking the button on the form with populating the data set for use with a Windows form . Filling the Categories data table in the DsCategories data set with data values from a SQL Server instance and displaying the values on a Windows form requires two m ore steps. First you need to invoke the Fill m ethod for the SqlDataAdapter object. Second you need to bind form controls, such as text boxes, to colum ns in the local Categories data table. Filling a Data Set and Binding Controls to I t A logical place to fill a data set for use with a form is the form Load event procedure. A single line of code in the tem plate will fill the data set. Run the line of code from the form Load event to make the contents for the data set available as soon as the form opens. The following code segment illustrates the syntax for invoking the SqlDataAdapter Fill m ethod to populate a data set. The event procedure is for Form1, which is the default startup object for a Windows application. The Fill method takes two argum ents in this situation. First you specify the data set name. Second you designate the DataTable nam e within the data set. You must nam e a DataTable object because one data set can hold multiple DataTable objects. Leaving out the DataTable nam e will cause an error. Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load SqlDataAdapter1.Fill(DsCategories1, “Categories”) End Sub After you fill the data set, you can bind it to controls on a form. For example, I added two text boxes to Form1 for the starter ADO.NET application. You can do this with the Toolbox just as in prior Visual Basic versions. What’s new is that there is now a DataBindings property. You can graphically bind the Text property for a text box control to a colum n in the Categories data table. Figure 1-7 shows how to bind the Text property for TextBox1 to the CategoryID colum n in the Categories data table. The Form1.vb Design tab shows TextBox1 selected on Form1. The Properties window reveals the assignment of the CategoryID colum n to TextBox1. Selecting a colum n from the Categories data table completes the task. I followed the sam e process for TextBox2, but I selected CategoryName instead. If you run Form1 by pressing the F5 key, you see the form with two text boxes showing the CategoryID and CategoryName colum n values for the first row from the Categories data table. While it is nice to see data in the text boxes, applications typically seek to allow users to at least browse through data. To
  • 31. enable browsing, you need controls that let a user navigate through the rows of the Categories data table. Figure 1-7. Use the DataBindings property to bind the Text property of a text box control to a colum n in a DataTable object. Navigating Through Row s A row of button controls can provide the basis for a navigation bar. All we need are Text property settings indicating the navigation each button provides and event procedures for the Click event of each button that navigates through the rows in the Categories data table. I added four button controls to Form 1 with event procedures to control navigation in response to click events. For example, Figure 1-8 shows the text boxes after the button control on the far right has been clicked. Notice that the last row (for CategoryID 8 in the Categories data table) shows in the top text box. Figure 1-8. Form 1 in the starter ADO.NET sam ple after the last- row button ( | ) has been clicked displays colum n values from the corresponding row in its text box controls.
  • 32. The following set of Click event procedures for Button1 through Button4 shows how easy it is to control navigation. The buttons from left to right navigate to the first row, the previous row, the next row, and the last row. The procedures update the Position property of the BindingContext property on the form for the Categories DataTable in the DsCategories1 data set. This manipulation, in turn, affects all text box controls bound to the Categories data table. Chapter 10 drills down m ore deeply into the object m odel supporting these manipulations. The important point to notice here is that the code doesn’t have to handle moving past the beginning or ending row because ADO.NET is smart about recognizing either end of a rowset, such as the Categories data table. Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click ’Move to the first row. Me.BindingContext(DsCategories1, “Categories”).Position _ = Me.BindingContext(DsCategories1, “Categories”). _ Position.MinValue End Sub Private Sub Button2_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button2.Click ’Move to the previous row. Me.BindingContext(DsCategories1, “Categories”).Position _ -= 1 End Sub Private Sub Button3_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button3.Click ’Move to the next row. Me.BindingContext(DsCategories1, “Categories”).Position _ += 1 End Sub Private Sub Button4_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button4.Click
  • 33. ’Move to the last row. Me.BindingContext(DsCategories1, “Categories”).Position _ = Me.BindingContext(DsCategories1, “Categories”). _ Position.MaxValue End Sub Using Query Analyzer Query Analyzer is your friend for debugging T-SQL statem ents. Because T-SQL is so important to SQL Server development, mastering this tool can be part of what makes you into a great SQL Server developer. W hat’s Query Analyzer For? Query Analyzer is one of the client tools that ships with SQL Server 2000. This is another way of saying that Query Analyzer isn’t part of the database server. You are authorized to use Query Analyzer, and the other client tools, by the allocation of a Client Access License to your workstation. Although the client tools don’t ship with MSDE 2000 (Microsoft SQL Server 2000 Desktop Engine), they are available with any regular version of SQL Server 2000, such as the Enterprise, Standard, Developer, and Personal editions. I think of Query Analyzer as sort of an I DE for running T-SQL statements. This client tool is a real help for anyone programm ing solutions for SQL Server. Query Analyzer will help you to easily and quickly debug your T-SQL code. Although you can program and debug T-SQL directly with Visual Basic .NET and ADO.NET, Query Analyzer provides a m uch richer environment that makes your T-SQL coding go m uch faster. Even if an application calls for running T-SQL inside of a Visual Basic .NET application, I often find it convenient to debug the statem ent in Query Analyzer before inserting the T-SQL code into my Visual Basic .NET application. There are at least five reasons to become comfortable with T-SQL, and using Query Analyzer m ay be one of the best ways to do that. • You can build richer query statem ents that return precisely the data you want without having to resort to a graphical query builder. I ndeed, some query operations, such as those perform ed by the UNI ON function, cannot be represented by graphical query designers. • You can create data manipulation statements for updating, inserting, and deleting rows. Graphical query builders aren’t always effective at creating these statements. • You can program security topics, such as creating SQL Server logins and controlling access to database objects and server adm inistration functions. • You can program the creation of databases and the objects within them , such as tables, stored procedures, and user-defined functions. Several chapters within this book include scripts to create databases and populate those databases with objects automatically. • You can take advantage of programm ing features, such as IF…ELSE statements, local variables, param eters, and return values to build flexibility and user interactivity into your applications. Many T-SQL samples are especially designed for use with Query Analyzer. For example, these samples set the database context for T-SQL code with a USE
  • 34. statement. This statement explicitly targets Query Analyzer and doesn’t run from most other SQL Server clients, such as Visual Basic .NET. Books Online, the SQL Server Help system, follows this convention with its samples. Therefore, a basic familiarity with Query Analyzer will help you to take advantage of the rich collection of samples in Books Online. I n addition, the T-SQL samples in this book follow the same convention. Therefore, this section gives you a brief introduction to Query Analyzer. You will have ample opportunity to reinforce and extend the understanding this section conveys with the T-SQL samples throughout the balance of this book. I n fact, the comm entary for these samples som etimes describes how to run code in Query Analyzer. Making a Connection w ith Query Analyzer To start Query Analyzer, click the Start button on the Windows taskbar; choose Programs, then Microsoft SQL Server, and then Query Analyzer. When you start Query Analyzer this way, you will be greeted with the Connect To SQL Server dialog box. Recall that Query Analyzer is a client tool. Therefore, you can use it with any SQL Server instance that you can connect to and for which you have access perm ission. If you are connecting to the local instance of SQL Server on your computer for which you are the adm inistrator, you can designate the SQL Server as “(local)” and choose Windows Authentication. (See Figure 1-9.) The settings in Figure 1-9 are suitable for connecting to SQL Server with any Windows login. Click OK to complete the connection to the server. Figure 1 -9. The connection settings for logging in to the local instance of SQL Server w ith W indow s authentication. Query Analyzer offers the normal flexibility in how you connect to a SQL Server instance. As I already noted, you can connect with any Windows login that a SQL Server instance recognizes. I n addition, you can use SQL Server authentication. I f you select SQL Server Authentication rather than Windows Authentication in the Connect To SQL Server dialog box, Query Analyzer enables the Login Name and Password text boxes so that you can specify a SQL Server login and password. I n addition, you can connect to any other SQL Server instance besides the local default one. I f you know the nam e of the instance to which you want to connect, type the nam e in the SQL Server combo box in the Connect To SQL Server dialog box. Otherwise, click the browse button (…) next to the combo box. This opens a dialog box that lists SQL Server instances currently active on the network to which your workstation connects. Select an instance nam e to specify a connection to that server.
  • 35. See Chapter 7 for more about SQL Server security and logging in to SQL Server instances with different types of logins. Until Chapter 7, one safe approach to running the samples is to connect as a m ember of the sysadmin server role, such as the SQL Server administrator. Members of the sysadm in server role have unrestricted perm ission on a SQL Server instance. Chapter 7 gives guidelines and procedures for restricting the perm issions for an application’s users. Running, Saving, and Opening T- SQL Scripts When Query Analyzer opens as described in the preceding section, it will connect a user to the default database for the login that the user specified in the Connect To SQL Server dialog box. The default is the master database unless a database adm inistrator changed the standard default database specification when adding a new login. Because m ost user-defined queries don’t interrogate the m aster database, which is a system database, you will usually want to change the database context before writing any SQL query statem ents. You can employ the USE statement for this. Just follow USE with the nam e of the database for which you want to write a query. The following statement directs Query Analyzer to run query statements against the pubs database (until another USE statement or some other specific instruction to use another database). The pubs database is one of the sample databases that is installed automatically with SQL Server 2000. USE pubs Figure 1-10 shows this sim ple SELECT statement for the authors table in the pubs database: SELECT au_fname, au_lname, state FROM authors WHERE contract = 1 The SELECT statement appears after the USE statement in the Editor pane, which is where you type T-SQL statements in Query Analyzer. The statement selects three colum n values from the authors table if a row has a contract column value equal to 1. You can see the result set from the query statem ent in the Results pane that appears below the Editor pane, as shown in Figure 1-10. Query Analyzer automatically displays the Results pane when you run a query, but you can also show and hide it by pressing Ctrl+ R. By default, Query Analyzer displays the result set in the Results pane within a spreadsheetlike grid. At the bottom of the Results pane are a Grids tab and a Messages tab. You can click the Messages tab to see general feedback from SQL Server about how a query statem ent operated. For exam ple, the Messages tab for the query in Figure 1-10 says, “(19 row(s) affected)”, which corresponds to the number of rows the query statem ent returns. Warnings and error feedback from a SQL Server instance appear in the Messages pane. You also can choose to display the result set in the Results pane as text in colum ns. I n that case, there is only a Results tab at the bottom of the Results pane, and both the result set and m essages are displayed in the pane. To specify whether you want to set the result set in a grid or in text, choose Options from the Tools menu, then choose the Results tab, and then use the combo box at the right of the Options dialog box to specify Results To Text, Results To Grids, or Results To File. Figure 1 -1 0. A query statem ent for the pubs database and its result set run from Query Analyzer.
  • 36. After creating a T-SQL script, you can save it so that you or others can reopen it and use it again later. Most of the sample files for Chapter 2 through Chapter 7 are saved scripts with the .sql extension. To save a script file for the first time or resave an existing script file with a new nam e, choose Save As from the File menu, navigate to a desired folder with the Save Query dialog box, enter a filename, and click Save. These steps will save the current script in the designated folder with the filenam e that you specify with the .sql extension. For example, I followed these steps to save the script shown in Figure 1-10 to my computer. I saved the file as AuthorsQuery.sql in the Chapter01 folder of the SQL Server Developm ent With VBDotNet directory on my C drive. There are several ways to open a script file. For exam ple, imm ediately after connecting to a SQL Server instance for a new Query Analyzer session, you can choose Open from the File menu, navigate in the Open Query File dialog box to the folder with the script file (.sql), highlight the filenam e, and click Open. These steps open an Editor pane in Query Analyzer with the saved script file. Figure 1- 11 shows the opened script file saved in the preceding paragraph in an Editor pane. Notice that the title bar for the pane includes the path along with the filename and extension. The Object Browser will also script objects for you. To automatically create a script for an object, right-click an object such as the Categories table, and choose Script Object To New Window As and then the Create command. This feature allows you to see the T-SQL script behind your favorite objects to learn how to
  • 37. make m ore objects like them or to help you change their design to m eet expanded objectives. As you build up your collection of databases and the objects within them , you might start to find special value in the Object Search component within Query Analyzer. You can open the Object Search dialog box by pressing the F4 key or by choosing Object Search from the Tools menu and then Open. You can open multiple Object Search dialog boxes at the sam e time. The dialog box lets you search for any object or subset of objects, such as views or stored procedures, by nam e or even a part of a nam e. Figure 1-13 shows an excerpt from the results in a search for any type of database object that begins with Categ in any database on the currently connected SQL Server instance. As you can see, objects beginning with Categ for their nam e are very popular in the Northwind database. (Other databases outside the excerpt shown also have objects beginning with Categ.) Figure 1 -11 . An opened T-SQL script from a saved .sql file. The path and filenam e in the title bar indicate the source of a .sql file. Selected Other Topics There’s lots more to Query Analyzer, but the preceding introduction equips you for the ways in which this book exploits the tool. I n this section, I briefly highlight a couple of my favorite other uses for Query Analyzer. The Object Browser is a convenient tool for exploring the databases and the objects within them on a connected SQL Server instance with a tree-type interface. You can use this Query Analyzer com ponent to examine the database objects within a database. You can show or hide the Object Browser by pressing the F8 key or by choosing Object Browser from the Tools m enu and then the Show/ Hide command. Figure 1-12 shows the Object Browser window expanded to display the colum n nam es and data type specifications for the Categories table (dbo.Categories) in the Northwind database. I often find it convenient to drill down into a database design and check the spelling of colum n nam es. Being able to quickly look up the data type for a colum n in a table is particularly convenient when you are declaring a search param eter for a co-lum n in a table; use the wrong data type, and you may not get a match, even with the right value. Figure 1-12 . The Object Brow ser opened to show the nam es and data types for the colum ns in the Northw ind database.
  • 38. Figure 1 -1 3. You can use the Object Search dialog in Query Analyzer to search for objects by nam e ( or even part of a nam e) .
  • 40. Chapter 2. Tables and Data Types This chapter targets the design and programm ing of SQL Server tables with T- SQL (Transact Structured Query Language). SQL Server database adm inistrators and developers use T-SQL for programm ing database administration and data access. By data access, I mean selecting records from a database. T-SQL is generally compatible with the SQL-92 standard endorsed by ANSI (American National Standards I nstitute) and ISO (I nternational Standards Organization). However, Microsoft optimized and stream lined T-SQL for use with SQL Server. Any developer who wants to use Visual Basic .NET to build custom SQL Server solutions will be severely handicapped without a good grasp of SQL Server data types and tables, as well as T-SQL. Several subsequent chapters in this part of the book will explore selected other database objects, such as views, stored procedures, and user-defined functions, from design and implem entation perspectives with T-SQL. The next part of the book builds on this foundation as it dem onstrates how to create custom SQL Server solutions with Visual Basic .NET. This chapter begins with an exploration of SQL Server data types. Next it provides an overview of different types of tables. A series of T-SQL samples illustrates core table design issues and solutions. These samples introduce you to programm ing techniques for SQL Server tables. By understanding how to script database objects, such as tables, you can readily duplicate those database objects across multiple servers. For example, a Visual Basic developer can build a solution on one server and then readily transport the objects for use on another server— just by running the scripts for the objects. You can also adapt the script from one object as a starting point for other, similar, objects. A clear understanding of table scripting techniques will help you to automate table design. This frees resources for focusing on the needs of clients for your databases. Chapter Resources There are two key resources for this chapter. First, a SQL Server database nam ed Chapter 02 illustrates m any of the design concepts used throughout this chapter. Second, a collection of T-SQL sample scripts illustrates coding techniques for creating tables and working with the resources within a table. The Chapter’s T-SQL Sam ple Scripts The T-SQL sample collection for this chapter illustrates key design and implem entation issues for scripting SQL Server database objects. All the sample scripts that you see in this chapter are available on the book’s companion CD. The samples are all saved with the .sql extension, so you can open and run each of them from Query Analyzer. As you learned in Chapter 1, Query Analyzer is a graphical tool that ships with Microsoft SQL Server 2000. As you read and run the sample scripts, you m ight find it helpful to learn more about the structure of the Chapter02 database by browsing it with SQL Server Enterprise Manager, which also was discussed in Chapter 1. The Chapter’s Sam ple Database
  • 41. The script in this section creates a new version of the Chapter02 database. Subsequent T-SQL code samples will create additional tables in the database and dem onstrate techniques for working with tables. Prepare to create the Chapter02 database by starting Query Analyzer and connecting to the SQL Server instance you are using. Log in as sa or with a user ID that belongs to the sysadmin fixed server role. This book drills down on security explicitly in Chapter 7, where you will learn how to fine-tune database and user security settings. When users connect to a SQL Server database through your Visual Basic .NET applications, they m ust identify them selves through the security accounts discussed in Chapter 7. Until that chapter, using a login that belongs to sysadmin will work for all sam ples. Copy or type the following T-SQL script into the Editor pane in Query Analyzer, and press F5 to run the script to create the database. Alternatively, you can open the script directly from Query Analyzer: choose Open from the File m enu, and then navigate to the location of the script. Notice that the first comment in the sample is “CreateSampleDB”— the nam e of the sample file. I use this convention for all the samples in the book to m ake it easier for you to locate and open them from Query Analyzer. Attaching a Database to a New SQL Server I nstance I regularly read on the SQL Server newsgroups of folks asking how to attach a database to a server. These developers want to take a database and its objects developed on one server and run them on another server. Their need can be as simple as copying a database application they are developing on their desktop to their laptop so they can work on it while away from the office. Alternatively, they may want to copy a database from headquarters or one branch office to one or more other branch offices. Although there are wizards for this kind of thing, it is nice to know how to program the administration of this kind of task for your own custom solutions. This capability liberates you from the canned wizard solution and gives you more flexibility in how you work with SQL Server. At its most elementary level, this can be as simple as attaching a pair of database files to a new server instance. In the context of this chapter, a completed version of the Chapter02 database is on the book’s CD. Therefore, you might care to copy a version to another instance of SQL Server besides the one you use to test the samples for this chapter. The instance can be on another computer or the same computer. Start to migrate the Chapter02 database by copying the Chapter02_dat.mdf and Chapter02_log.ldf files from the CD to the Data folder for the SQL Server instance to which you want to attach the completed database. After clearing the read-only attribute settings for the files, you can run the following script from Query Analyzer. The script attaches the chapter’s two database files to the default instance of the SQL Server to which Query Analyzer connects. By changing MSSQL to MSSQL$MYOTHERI NSTANCE, you can attach the database files to a SQL Server instance named
  • 42. MYOTHERINSTANCE. You must copy your database files to the Data path for the SQL Server instance in the sp_attach_db statement before running the script. --AttachSampleDB --Run the script from the master database. USE master --Update the paths for the data and log files so they --are appropriate for your computer. EXEC sp_attach_db @dbname = N’Chapter02’, @filename1 = N’c:Program FilesMicrosoft SQL ServerMSSQLDataCha pter02_dat.mdf’, @filename2 = N’c:Program FilesMicrosoft SQL ServerMSSQLDataCha pter02_log.ldf’ The initial USE statem ent in the script specifies the source database so that the sample runs from the SQL Server m aster database. Next the script rem oves any prior version of the Chapter02 database on the server. This ensures that you can always create a new copy of the database. After rem oving any prior version, the code invokes the CREATE DATABASE statem ent. This statement assigns the logical filenam es Chapter02_dat and Chapter02_log to the data and log files for the database. Although your SQL Server databases can have m ore files, these two are necessary for populating a database and perform ing backup operations. Update the operating system file paths so that they are appropriate for your computing setup. --CreateSampleDB --Execute statements from the master database. USE master GO --Drop any prior version of Chapter02 database. IF EXISTS (SELECT * FROM INFORMATION_SCHEMA.SCHEMATA WHERE CATALOG_NAME = N’Chapter02’) DROP DATABASE Chapter02 GO --Create new version of Chapter02 database. CREATE DATABASE Chapter02 ON (NAME = Chapter02_dat, FILENAME = ’c:program filesmicrosoft sql servermssqldataChapter02_dat.m df’, SIZE = 1) LOG ON (NAME = Chapter02_log, FILENAME = ’c:program filesmicrosoft sql servermssqldataChapter02_log.l df’, SIZE = 1, MAXSIZE = 5) GO
  • 43. Data Types for Tables Tables are the building blocks for SQL Server applications because they store the data for the entities that an application models. Likewise, colum ns are the building blocks of tables because tables store their data as colum n values. SQL Server applications can often have tables with numerous rows, so it is important to specify the data type for columns to ensure that they use the m inim um amount of storage. When you specify the data type, you are indicating the kind of data that the colum n is going to contain. Making these assignm ents correctly speeds the perform ance of your SQL Server applications while also conserving storage space. I n addition, the validity of your database m odel for a real-world system can depend on the use of proper data types. In many circumstances, your applications can denote data with one of the data types built into SQL Server— the system data types. When your application needs more definition than these system data types allow natively, you can create user- defined data types that refine the system data types. However, your ability to fashion valuable user-defined data types depends on your grasp of the system data types. If you are fam iliar with data types, you may want to skip this section and refer to it as needed. But if you are new to SQL Server programm ing or need a refresher on data types, read on. System Data Types It is useful to think about the system data types in six groups. I n addition to the six hom ogeneous categories, there is a collection of special, or m iscellaneous, system data types. The six hom ogeneous groups of data types pertain to: • Character data • Unicode data • Num eric data • Monetary data • Date and Tim e data • Binary data Character Data Character data consists of alphanum eric character sequences. Therefore, you can represent any combination of numbers and words with character data, such as “123 Mulberry Lane”, “$1,000,000”, “Your nam e goes here: ” or “Rick Dobson”. SQL Server has three character data types: char, varchar, and text. The following table briefly summarizes them. 'DWD 7SH 1DPH 'DWD7SH'HVFULSWLRQ char For fixed-length character data up to 8000 characters. Use char(n) to specify, with n as the number of characters. The storage size is n bytes. Appropriate when all the column values are the same length (or when this is very nearly true). varchar For variable-length character data up to 8000 characters. Use varchar(n) to specify, with n as the maxim um number of characters.
  • 44. The storage size for any varchar colum n value is the actual size, where 1 byte equals 1 character. Appropriate when there is substantial variability in length between colum n values. text For variable-length character data that can grow to 231 -1 (2,147,483,647) characters in the SQL Server instance’s code page format. Although som e of these code pages perm it double-byte format for representing characters, the length of a text data type colum n value is still the number of characters, where 1 character equals 1 byte. SQL Server supports im plicit and explicit conversion between data types. SQL Server handles implicit conversions automatically; you use the CAST and CONVERT functions to convert between types explicitly. The CONVERT function is a proprietary extension of the CAST function that offers extra conversion capability not available from CAST, which is SQL-92 compliant. See the “CAST and CONVERT” topic in SQL Server Books Online for m ore detail on conversion between SQL Server data types. Im plicit conversions don’t depend on the transform ation of a value by the CONVERT or CAST function. Im plicit conversion also applies to the conversion of a result from com bining or comparing two or more values with different data types. A variety of Books Online topics clarify implicit conversion, including the “CAST and CONVERT” topic. For example, see the “Data Type Conversion,” “Data Types and Table Structures,” and “Data Type Precedence” Books Online topics. You can use the Search tab in Books Online to search for these topics. The Books Online search engine will often return multiple topics for any search string, even when you specify a precise search topic title. Scan the list of titles returned by the search engine for the exact one you seek. Unicode Data Unicode is a 16-bit character encoding standard. SQL Server data types for Unicode correspond to SQL character data types— nchar, nvarchar, and ntext for fixed-length, variable-length, and very long Unicode data. One key distinction is that the Unicode format for translating bits to characters relies on a single standard translation table that uses 2 bytes per character. The character data formats use a collection of different code pages most of which assign 1 byte per character. This distinction gives Unicode format the capacity to represent m ore than 65,000 characters, while non-Unicode character data typically represents only 256 characters at a tim e (or per code page). The Unicode codes that have been assigned represent characters in m ost of the written languages of the world. Character data uses system-level tables called code pages to determ ine how to translate bits to characters. Different countries can rely on different code pages to represent their character set. For applications that run in many different countries, it can be challenging to find a single code page with valid and consistent bit-to-character translations for all languages. Using Unicode data resolves this problem because its code page accommodates 216 characters. The price for this easier cross-country applicability is that each character has a size of 2 bytes instead of the 1 byte per character. As a result, the maxim um number of characters for Unicode data types is half that of corresponding character data types. The following table sum marizes the three Unicode data types. These data types align with the character data types, but they have different length and applicability. 'DWD7SH 1DPH 'DWD7SH'HVFULSWLRQ nchar For fixed-length character data up to 4000 characters in length with a Unicode data format. Use nchar(n) to specify, with n as the number of
  • 45. characters. The storage size in bytes equals twice the number of characters. Corresponds to the char data type in terms of applicability except for its broader usefulness for representing characters from multiple languages. nvarchar For variable-length character data up to 4000 characters in length. Use nvarchar(n) to specify, with n as the maximum number of characters. The storage size for any nvarchar colum n value is the actual size, where 2 bytes equal 1 character. Corresponds to the varchar data type in terms of applicability except for its broader usefulness for representing characters from m ultiple languages. ntext For variable-length character data that can grow to 230 -1 (1,073,741,823) characters in the Unicode code page format. Corresponds to the text data type in term s of applicability except for its broader usefulness for representing characters from multiple languages. Note In the case of column data type specifications, precede the character data type name with an n to denote the matching Unicode data type name. Represent character constants in SQL Server with single-quotation mark delimiters. Use a leading N to represent a Unicode constant. For example, a character constant appears as ‘my character constant’ . However, the matching Unicode equivalent appears as N’my Unicode constant’ . Num eric Data Num eric data consists of numbers only. You can perform arithm etic operations on numeric data, and you can compare num eric values along a num eric scale, which can differ from comparisons based on collations for character data and Unicode data. SQL Server has three general categories for num eric data: integer data, decimal data, and approximate data. Within each of these categories, there are one or more specific data types. Beyond that, the num eric data categories denote different classes of num bers or ways of representing numbers. I nteger Data Integer data types denote values that SQL Server represents exclusively as whole numbers. The integer data types include tinyint, smallint, int, and bigint. The data types differ primarily in the magnitude of the number that they can represent, but the tinyint data type differs in that it cannot represent negative values as can the others. I nteger data types, particularly int, are comm only used along with the IDENTI TY property to specify autom atically incrementing colum n values that serve as the primary key for a table. The next table lists the integer data types along with brief summaries of their capabilities. Your applications should generally use the sm allest data type possible. However, use a data type with sufficient range for your needs because SQL Server rejects column values outside the limits for a data type. Calculations, such as aggregations in views, work differently for tinyint and smallint values. I n these cases, SQL Server automatically prom otes the return value to the int value
  • 46. range. Therefore, the sum of a set of tinyint colum n values can exceed 255, but no individual tinyint colum n value can exceed 255. The tinyint/ smallint promotion policy doesn’t apply to calculations based on int colum n values; SQL Server doesn’t automatically promote a return value outside the int lim its— even if the result is within the bigint limits. I nstead, SQL Server returns an error. I n addition, the bigint data type doesn’t work with all functions that the other integer data types can use, and there are special functions for selected tasks, such as counting instances and returning rows affected by queries, in which the quantities exceed the int range to fall in the bigint range. See the “Using bigint Data” topic in Books Online for m ore detail on the special restrictions that apply to the bigint data type. 'DWD7SH 1DPH 'DWD7SH'HVFULSWLRQ tinyint For values in the range 0 through 255. Each tinyint column value is 1 byte long. smallint For values from -215 (-32,768) through 215 -1 (32,767). Each smallint column value consum es 2 bytes of storage. int For values from -231 (-2,147,483,648) through 231 -1 (2,147,483,647). Each int column value requires 4 bytes of storage. bigint For values from -263 (-9,223,372,036,854,775,808) through 263 -1 (9,223,372,036,854,775,807). Each bigint column value requires 8 bytes of storage. Decim al Data The decimal data category is a single num eric category with two equivalent SQL Server data types: num eric and decimal. You can use them interchangeably, but decimal is probably the more comm on data type nam e. Like the integer data types, the decim al data types precisely represent values. However, decimal data types differ from integer data types in three ways. First, decim al data type values allow for places after the decimal. (Recall that integer data types restrict you to whole numbers.) Second, decim al data type specifications permit a variable precision (or total number of digits). The total number of digits, which can range from 1 through 38, includes digits to the right and left of the decimal point. Third, you can designate a decimal data type for a colum n with variable scale (or digits to the right of the decimal point). Note The decimal data type in SQL Server 2000 and the Decimal data type in Visual Basic .NET aren’t the same. The Decimal data type in Visual Basic can represent numbers with values from 1 through 28 digits to the right and left of the decim al point. This distinction (1 through 28 vs. 1 through 38) is important. Unless proper precautions are taken, you can encounter overflow errors as you extract column values with a decimal data type from a SQL Server table into your Visual Basic .NET application. If you know the numbers in the SQL Server table exceed the values that Visual Basic .NET can represent with its Decimal data type, consider representing the SQL Server decimal data type values with another data
  • 47. type in Visual Basic .NET, such as Double, which has a range from -1.79E + 308 through 1.79E + 308. Designate a decimal category value with decim al(p,s) or num eric(p,s). The p value represents the precision; the s value denotes the scale. The precision m ust be less than or equal to 38 but greater than or equal to the scale. The scale m ust be less than or equal to the precision, but the scale has to be greater than or equal to 0. The maxim um data range for decim al type values is from -1038 + 1 through 1038 - 1. This range substantially exceeds the limits of any integer data type. The sam e holds true for the two m onetary data types that SQL Server offers. (We’ll review these shortly.) Note Columns with the decimal data type specification can also serve as an auto-incrementing primary key when you assign an IDENTITY property to the column. Set the scale to 0 for this application of the data type. The length in bytes for the decimal data type specification depends on the precision. The following table summarizes the relationship between storage requirem ents and precision for decim al data types. 3UHFLVLRQ 6WRUDJH%WHV 1–9 5 10–19 9 20–28 13 29–38 17 Approxim ate Data All the prior num eric data types precisely represented data values. This avoids rounding error. The two approximate data types allow you to represent data values without perfect precision (but extrem ely close to the exact value). I n exchange for reduced precision requirem ent, the approximate data types offer a much wider range than the previous data types. When you need to represent numbers beyond the range of the preceding num eric category data types, the approximate data types offer a viable alternative (for example, in engineering applications working with very large or sm all values). Approxim ate data types also enable your applications to use less storage space when reduced precision is acceptable for your needs. The two SQL Server approximate data types are real and float. The real data type offers the smaller range and precision, but it requires just 4 bytes per data value. Its range extends from -3.40E + 38 through 3.40E + 38. The float data type extends from -1.79E + 308 through 1.79E + 308, but each float data type value requires 8 bytes of storage. Therefore, the float data type offers increased range and precision relative to the real data type, but float data type values consume 4 more bytes per column value. Both data types follow the IEEE (I nstitute of Electrical and Electronic Engineers) 754 specification for approximate data types. SQL Server uses the round up mode, which is one of four rounding m odes in the 754 specification. Monetary Data SQL Server has two data types for representing m onetary data. Both are accurate to the nearest ten-thousandth of a monetary unit. The smallmoney data type has
  • 48. a range from -214,748.3648 through 214,748.3647. SQL Server requires 4 bytes of storage for each value with this data type. The money data type has a range that starts at -922,337,203,685,477.5808 and runs through 922,337,203,685,477.5807. This data type consumes 8 bytes of storage for each colum n value. With either data type, you can use a currency symbol, such as $, and a decimal point when inputting values, but you shouldn’t input values with commas. I n other words, use $1234.5678 instead of $1,234.5678. As you can see, the two m onetary data types are two possible variations of the decimal data type in term s of its precision and range. For example, you can represent smallmoney data types with decimal(10,4). The m oney data type has decimal(19,4). When you need to represent m onetary data with other formats, use alternative decimal specifications, such as decim al(19,2) or decimal(38,2). Date and Tim e Data SQL Server has two data types for internally representing date and tim e values. These data types differ in precision as well as range. Before diving into the details of each data type, note that SQL Server data types for date and time values always contain both a date and a tim e value. I n addition, while SQL Server uses one of two internal form ats for storing date and time values, it displays date and time values as strings. I n addition, you will frequently input a new date or tim e colum n value as a string. When designating a date or a tim e value with a string, you can designate just the date, just the tim e, or both the date and the time. The smalldatetime data type has the shorter range of the two data types for dates and tim es. This data type includes dates from January 1, 1900, through June 6, 2079. Within any given day, smalldatetime data type values represent time from 12: 00 A.M. (midnight) through 11: 59 P.M., to the nearest minute. The smalldatetime data type rounds down to the nearest m inute for all values of 29.998 seconds or less. Conversely, it rounds up to the nearest m inute for all values of 29.999 seconds or m ore. You can designate a datetim e value with a character string to the nearest one-thousandth of a second, such as ' January 1, 1900 12: 00: 29.998' , for implicit conversion as input to colum ns with a small- datetim e data type specification. Each smalldatetime colum n value requires 4 bytes of storage— two for the date and two for the tim e. The other data type for date and time values is datetim e. Values in datetim e format can range from January 1, 1753, through Decem ber 31, 9999. As with the smalldatetime data type, the datetim e data represents tim e from midnight. However, the precision is to the nearest 3.33 m illiseconds. Therefore, you can represent the first tim e value after m idnight as ' 00: 00: 00: 003' . SQL Server rounds datetime values internally to the nearest millisecond within its precision. For example, tim e values to the nearest millisecond progress from ' 00: 00: 00: 000' to ' 00: 00: 00: 003'to ' 00: 00: 00: 007' . The datetime data type specification consum es 8 bytes of storage— 4 bytes for the date and 4 bytes for the time. Binary Data Binary data represents data in its native binary format. For example, a GUID, or globally unique identifier, appears as a 16-byte binary data stream. SQL Server represents each byte with two hexadecim al numbers. The decimal num ber 17, for example, appears as 11 in hexadecimal format, which corresponds to 00010001 as a byte. Hexadecimal formatting uses the letters A through F to denote the decimal values 10 through 15. Therefore, the hexadecimal number 9F translates to 159 in decimal format, or 10011111 as the bits for a byte. SQL Server frequently denotes hexadecim al values for input and display with a leading 0x; that is, a zero followed by a lowercase x. Of course, the internal representation contains just the binary representation for data.
  • 49. There are three data types for binary data in SQL Server. When you are working with data strings of 8 KB or less, use either binary or varbinary. For longer binary data streams, such as Word docum ents or Excel worksheets in Office 97 or Office 2000, use the image data type. The following table summ arizes the three binary data types. 'DWD7SH 1DPH 'DWD7SH'HVFULSWLRQ binary For fixed-length binary data up to 8000 bytes in length. Use binary(n) to specify, with n as the number of bytes. The storage size is n bytes. Appropriate when all the column values are the same length. varbinary For variable-length binary data up to 8000 bytes in length. Use varbinary(n) to specify, with n as the maximum number of bytes. The storage size for any varbinary colum n value is the actual size of a bit stream in bytes. Appropriate when not all colum n values are the sam e length. image For variable-length character data that can grow to 231 -1 (2,147,483,647) bytes. Use this data type when your binary data exceeds 8 KB for any column values. Although the data type’s name is image, it accomm odates any binary data, including bitmap or GI F image files as well as Word .doc files. Special System Data Types Four remaining system data types complete the set available for specifying colum ns in a table: timestamp, bit, uniqueidentifier, and sql_variant. These data types don’t fit into any one category. This section addresses each of the data types individually. The timestamp data type is a binary variable that tracks the latest addition or revision of a row throughout a database. I t is a sequential number— somewhat like an autonumber in Access or an integer with an IDENTITY property setting in SQL Server. However, it pertains to an entire database instead of a single table within a database. Whenever a user adds a new row or revises a value in a row of a table with a tim estamp colum n, the timestam p colum n value increases by 1. SQL Server represents this tim estamp value as an 8-byte binary value. I f the largest tim estamp value throughout any row in any table of a database is 0x13579BDF, the next tim estamp value will be 0x13579BE0. Note Columns declared with a timestamp data type don’t contain datetime or smalldatetime values. Microsoft announced its intention to reference the timestamp data type as the rowversion data type in future SQL Server versions. The bit data type is for representing True/ False or Yes/ No data. In SQL Server, a bit data type with the value 1 is equivalent to True or Yes. The bit value 0 corresponds to False or No. You can, optionally, make a bit data type nullable so that it can have the value 0, 1, or NULL. Values in bit form at consum e 1 bit, and SQL Server packs bit data values 8 bits to the byte to conserve space. Therefore, 1 through 8 bit data type columns in a row require 1 byte of storage. The ninth through the sixteenth bit data type colum ns add a second byte of storage for each row. The uniqueidentifier data type specifies a 16-byte GUI D. Since a GUI D is unique in space and tim e, the uniqueidentifier is a candidate for identifying rows across
  • 50. multiple installations of SQL Server, such as by state in the United States or by country. However, because of its size, using a uniqueidentifier can slow an application and consum e storage disproportionately. The severity of this uniqueidentifier weakness escalates with the number of rows in a table. Consider using an int (or even a bigint) colum n with an I DENTI TY property along with a second column to denote place. This alternative approach to uniquely identifying records at m ultiple locations can m ake an application run faster and consume less storage. Also, the uniqueidentifier doesn’t work well for the full range of SQL Server functions; see the “uniqueidentifier” and “Using uniqueidentifier Data” topics in Books Online for more detail. A sql_variant data type specification enables a colum n in a table to accept a mixed collection of data values based on any other system data type except text, ntext, timestamp, image, and sql_variant. All other system data types require the values in a colum n to be of one data type. You can’t enter character data into a colum n with an int data type. With a sql_variant data type specification, a single colum n can contain char, int, and datetime data values all in a single colum n. The sql_variant data type name derives its nam e because of its sim ilarity to the Visual Basic Variant data type. The m ixed data type values in a sql_variant column can cause its values to behave differently when you’re comparing sql_variant values with values of another data type or when you’re sorting a table by the values in a sql_variant colum n. See the “Using sql_variant Data” topic in Books Online for m ore details on this topic. 'DWD7SH1DPH 'DWD7SH'HVFULSWLRQ timestamp The timestamp data type has a binary(8) data form at unless you make it nullable. A nullable timestamp data type has a varbinary(8) data format. SQL Server automatically generates timestamp values; your application or your users have no need to populate a tim estamp colum n. bit Prim arily for modeling attributes that can have one of two states. However, the data type also does perm it NULL values. SQL Server optim izes storage of bit data type values so that the first 8 take up to 1 byte, the next 8 a second byte, and so on. uniqueidentifier A 16-byte binary num ber that represents its value as 32 hexadecimal characters. The format for displaying the - hexadecimal characters is xxxxxxxx-xxxx-xxxx-xxxx- xxxxxxxxxxxx. Use the NewID function to generate a new uniqueidentifier. You can specify a uniqueidentifier value either with a character string representing the 32 hexadecimal characters or with a binary number. However, always use the NewID function when you must ensure the uniqueness of the uniqueidentifier value. sql_variant For storing multiple other kinds of data type values in a single column. This SQL Server data type bears a resemblance to the Visual Basic Variant data type. Note Two additional SQL Server types do not represent individual numbers or string values. These are the table and cursor types. The table type can represent a whole result set of values, such as a table returned by a user-defined function. Chapter 5 demonstrates the use of this SQL Server type. The SQL Server cursor type refers to server-side cursors. Many
  • 51. developers prefer to avoid this type because it can degrade database performance. User-Defined Data Types User-defined data types enable you to define custom data types based on system data type and nullability. You and your developer team can then apply these user-defined data types in m ultiple tables throughout a database. The scope of a user-defined data type is the current database, but you can copy the script defining a user-defined database to other databases. Use the sp_addtype and sp_droptype system stored procedures to add and drop user-defined data types to and from a database. When you add a user-defined data type with sp_addtype, specify its name, base data type, and nullability by position or with param eter nam e assignments. After creating a user-defined data type, you can assign it to table colum ns throughout a database. If you add a user-defined data type to the m odel database, every new user-defined database will have the user-defined data type. This is because SQL Server uses the model database as a starting point for all user-defined databases. The sp_droptype system stored procedure can generally remove a user-defined data type from a database, but this system stored procedure won’t succeed if any tables exist with colum ns defined by the user-defined data type. Note System stored procedures, such as sp_addtype and sp_droptype, gain focus as a general topic in Chapter 4. The sp_addtype system stored procedure allows you to specify a user-defined data type in terms of its base data type. For exam ple, you can designate a postal code data type with a char(5) or a char(9) base data type. However, users can still enter values other than numbers in the postal code character fields. To specify constraints that apply to user-defined data types, designate a SQL Server Rule object and bind the rule to the user-defined data type; use the sp_bindrule system stored procedure to bind a rule. Then developers can specify new tables with columns specified by user-defined data types that convey the rule. This approach for applying rules bound to user-defined data types works for the creation of new tables but not for the modification of existing colum ns in existing tables. For implem entation details of user-defined data types, see the Books Online topics for sp_addtype, sp_droptype, and sp_bindrule. Note Examine the pubs sample database in Enterprise Manager for several examples of how to apply user-defined data types in a database. Scripting Tables The “Data Types for Tables” section earlier in this chapter described the most fundam ental elem ents of a table. However, it didn’t demonstrate how to apply those elements to the construction of a table. This section introduces T-SQL statements and syntax rules for creating tables. The section also exam ines issues
  • 52. relating to the processing of selected data types and the modifying of a table’s design. Creating a Table You use the CREATE TABLE statem ent to create a new table. Before invoking the statement, you must designate a database to hold your new table. Specify this database with the USE statement. The following sample script assigns its new table, EmailContacts, to the Chapter02 database; recall that the “Chapter Resources” section includes a script for creating a fresh copy of this database. Within the CREATE TABLE statem ent, you can specify colum n nam es for the table along with data types and other settings for each colum n. The script creates a table nam ed EmailContacts with four colum ns named ContactID, FirstName, LastNam e, and Email1. The ContactID column serves as a primary key. The colum n’s specification includes a name (ContactID), a data type (int), and a specification for its nullability (NOT NULL); and the last keyword designates the colum n as a primary key. Because the table includes additional columns, the colum n declaration ends with a comma. The remaining three declarations within the CREATE TABLE statement specify colum ns for holding contact data. Each of these declarations begins with a colum n nam e followed by a data type and a nullability assignm ent. A comma separates the declaration for each colum n. I n contrast with the colum n serving as the primary key for the table, the three colum ns for storing contact data can be null. This allows a user to create a row for a contact at one tim e and then populate the row at a later tim e. SQL Server has a default setting for the nullability of colum ns that you can configure. The default configuration is for ANSI compatibility, which allows nulls for new colum ns. Nevertheless, it is good practice to designate the nullability of colum ns explicitly. --CreateEmailContactsTable_01 --Execute statements after USE from Chapter02 database USE Chapter02 --Create EmailContacts with three columns. CREATE TABLE EmailContacts ( ContactID int Not Null PRIMARY KEY, FirstName nvarchar(20) NULL, LastName nvarchar(35) NULL, Email1 nvarchar (255) NULL ) GO The script will work the first tim e you run it. However, if you try to run the script a second tim e, it will fail with a message rem inding you that the EmailContacts table is already in the database. I n order to rerun the CREATE TABLE statement successfully, you can conditionally drop the Em ailContacts table. You need to drop the table conditionally because the DROP TABLE statement will fail if the table isn’t already in the database. While you’re editing the preceding script, it might be nice to add some data and then run a simple SELECT query to see how to insert and retrieve data from the table. The next script dem onstrates techniques for achieving these results. This next script illustrates broad design issues for running T-SQL scripts in Query Analyzer. For example, the USE statem ent designates a source database to use for running the statem ent. USE isn’t a T-SQL statement; rather, it is a keyword for Query Analyzer that instructs it to connect to a database on the server for the current Query Analyzer session. I f the database doesn’t exist on the connection, Query Analyzer returns an error m essage. Notice also that batches of T-SQL statements are delim ited by the GO keyword. This is a keyword for Query
  • 53. Analyzer as well. The GO keyword instructs Query Analyzer to interpret and run the preceding T-SQL statements. Position the GO keyword in scripts to ensure that a set of statements will run before you start another set of statements. This keyword is convenient for isolating errors. After the USE statem ent, the script tests for the prior existence of the Em ailContacts table. I f it does exist in the current database, the script invokes a DROP TABLE statem ent to rem ove the prior version of the table. An IF EXISTS statement based on an INFORMATI ON_SCHEMA view is a common m eans of testing for the existence of a database object. I NFORMATI ON_SCHEMA views return m etadata about m any classes of SQL Server database objects besides tables. A subsequent section dwells on this topic more specifically. The CREATE TABLE statement is identical to the preceding T-SQL listing. However, in the context of this sam ple, you can rerun the script repeatedly without encountering an error message about the object already existing. After creating the table, the following listing populates the table with two rows. I t uses the INSERT I NTO statement to add rows. Because these statements designate colum n values for all the table’s colum ns in the order in which they appear in the table, the statem ents can simply reference the VALUES keyword followed by the colum n values for a row. --CreateEmailContactsTable_02 --Execute statements after USE from Chapter02 database. USE Chapter02 GO --Remove prior version of EmailContacts if it exists. IF EXISTS ( SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME = ’EmailContacts’ ) DROP TABLE EmailContacts --Create EmailContacts with three columns. CREATE TABLE EmailContacts ( ContactID int Not Null PRIMARY KEY, FirstName nvarchar(20) NULL, LastName nvarchar(35) NULL, Email1 nvarchar (255) NULL ) GO --Populate EmailContacts and run a SELECT query. INSERT INTO EmailContacts VALUES(1,’Rick’, ’Dobson’, ’[email protected]’) INSERT INTO EmailContacts VALUES(2,’Virginia’, ’Dobson’, ’[email protected]’) SELECT * FROM EmailContacts GO A SELECT statement closes the script. When the SELECT statement runs, Query Analyzer displays the result set in the Results pane, as shown in Figure 2-1. Figure 2 -1 . The result set from the script to create, populate, and list values for the Em ailContacts table.
  • 54. View ing Metadata Metadata is the information about data, such as a database server and its objects, including databases, tables, and keys. So far, this chapter has reviewed two main T-SQL samples. One of these created a database— Chapter02. The other created a table— EmailContacts—within the database. I n turn, the table has several colum ns, and one of those colum ns is defined as a primary key. I t is often useful to be able to generate reports that contain information about the contents of a database server and its objects. For example, the previous sample showed that determ ining whether a table already existed in a database would allow your application to avoid an error— trying to create a new table with the sam e name as an existing one. SQL Server I NFORMATION_SCHEMA views can derive this kind of information for your applications. This section exam ines this capability by dem onstrating it. The following T-SQL script includes four batches of statem ents— each terminated by the GO keyword— that illustrate different uses and form ats for deriving metadata with INFORMATI ON_SCHEMA views. The initial batch dem onstrates the syntax for reporting the databases within a connection. I n this case, the connection is the one based on your login to Query Analyzer and the master database for the SQL Server instance. The master database is one of the system databases that SQL Server creates when you install it. This database is vital to the proper operation of a SQL Server instance. One function of this database is to track information about all the databases on a SQL Server instance. The SCHEMATA view of the I NFORMATI ON_SCHEMA returns a high-level summ ary of that information. The next batch of T-SQL statements begins by changing the context for the statements from the master database to the Chapter02 database. This batch returns all the colum ns from the TABLES view of the INFORMATION_SCHEMA for which the table’s nam e doesn’t begin with either sys or dtp. While users can create tables with nam es that begin with either of these character strings, SQL Server uses tables beginning with these characters to m anage a database. Therefore, excluding tables that begin with those characters can return information about user-defined tables. Of course, if your application creates any tables beginning with these prefixes, they won’t appear in the result set for the TABLES view. Note The TABLES view for INFORMATION_SCHEMA returns
  • 55. Random documents with unrelated content Scribd suggests to you:
  • 56. “My dearest Peter,—I am sending this letter to you by your father, because I want it to reach you without fail. Letters by post go wrong sometimes, and I don’t want this to go wrong. When I have finished it, I shall put it into his despatch-box myself. “When your father comes back from his visit to you and Silvia, he will not find me here. It is no use mincing words, so I will tell you straight out that I can’t stand him any longer. It would not have answered my purpose just to go away from him for a month, for I should have felt all the time that at the end of a month I should have to come back; I should have been on the end of the string still. As it is, I shall stop away just as long as I choose. I shall be free. I want a holiday without any tie whatever. When I mean to come back (if I do) I shall write to him and ask him if he will take me back. I don’t know how long it will be before I want to. It might be a fortnight, or it might be a year, or it might be never. I shall simply stay away from him, at some pleasant place which I have selected, until I feel better. “While you were living with your father and me I could just get along; but since you have gone I can’t get along at all. We weren’t much to each other, for all my individuality—isn’t that what they call it?—had long ago been hammered back into me. I was like a small person in a large suit of armour. But somehow you were a part of me, and while you were there I couldn’t go away. “I ask you, my dear, not to make any attempt to find me, and I want you to persuade your father not to. I shall be quite comfortable, and as I am never ill I don’t see why I should begin to be so now. I shall go to a nice hotel, where I shan’t have to order lunch and dinner or add up bills. It is astonishing how many nice hotels there are, quite moderate in price, which will just suit me. “Now this may seem unkind, but the fact is that I don’t want to hear a word from either you or your father. You and I have nothing in common; in fact, I have nothing in common with anybody, and I only want to be left alone in peace, and not to be reminded of the last twenty-five years of my life at all. I want not to be bothered with anybody. I want to get up and go to bed when I choose, and go for my walk, and read my book, and play patience. You and I have never loved each other at all, so there’s no use in pretending to be pathetic over that now. Before you were old enough to understand, I hadn’t got any feeling left in me, or, at least, it was hammered
  • 57. right inside me. If any time during these last ten years I had died, you wouldn’t have missed me, though if you had died I should have missed you to the extent, anyhow, of your absence making my life with your father quite intolerable. I don’t bear him the slightest ill will, and I hope he’ll bear me none. He has excellent servants, and they will make him quite comfortable, which is all he wants. But I’ve got too much sense to remain with him any longer. “He has been saying great things lately about the immense sums of money he will get for his series of cartoons, so that I have no scruple in withdrawing from him the £600 a year which is my own income. I can’t be certain, of course, whether he has not been multiplying everything by ten, in order to glorify himself, but I suppose there is some truth in it all. Anyhow, he has got a cheque from Mrs. Wardour for a thousand guineas, because he showed me that. He was in great spirits that night, dancing round the table and singing and drinking quantities of port. And that, it appears, is nothing to what he is about to get for the rest of his great series.” Peter took his eyes off the neatly written sheets for a moment and gave a great gasp. The figure of his mother, as he was accustomed to behold it, veiled and still, and sitting in shadow and never giving a sign of individual life, had suddenly cast off its concealment and tranquillities, and stood out violently illuminated. That smooth, polished object which had lain inert so long in the midst of railway guides, had proved itself to be a live shell which, without any warning or preliminary sizzling, had exploded. He himself was unhurt, though immeasurably astonished and startled, and he exulted in the fact that the thing had been alive after all, carrying within it such store of devastating energy. His own marriage, his departure from home, had set off the fuse; he had been, all unconsciously, the controlling agent. He dived again into this most lucid report of the explosion, observing with regret that there were but a couple of pages more. At the moment Silvia appeared at the door from the terrace into the drawing-room close behind where he sat. “Peter, is that you?” she asked. “Yes; one minute. Or come here, Silvia. Take these sheets and read them without saying anything till I’ve finished. It’s a letter from my mother.”
  • 58. He buried himself in the remainder of the letter, hardly hearing Silvia’s gasp of surprise as she came to the second paragraph. “Now I want you,” the narrative continued, “to consider this before you pass any judgment on what I have done. I am injuring nothing and nobody, except your father’s vanity, and I have no doubt he will find some explanation of my leaving him which will quite satisfy him. He will not be the least less happy without me, nor will you. I have got no friends, for I am not the sort of person who can make friends or wants them; I have been hammered, as I have said, into myself, and I break no ties the severance of which is painful for others any more than for me. I see so few people, and those so very occasionally, that there need be no scandal of any kind; your father will only have to say, about once a month, that I am on a visit in the country, which is quite true. “My solicitor knows where I am, and from time to time he will let you have a note from me, saying how I am. As for news, I shall have none; I shall take my walk, and read my book, and entertain myself very well, and I shall be very happy, because I shall be free. I rather believe that you are sufficiently like me to understand that, for you have always kept yourself independent of everybody. “Finally, I leave it to you (no doubt you will consult Silvia) as to whether you let your father find out that I have gone when he returns home, or whether you tell him. I think personally that it would be wiser to tell him, because when he got home and found the few lines (not like this long letter) which I have left for him there, just to say I have gone, he might make some dreadful scene and upset everybody. But that I leave entirely to you. “All the wages and books were paid up to the end of last week. The bills, with their receipts, are in their place in the third drawer of my knee-hole table. “Your affectionate mother, “Maria Mainwaring.” Peter thrust the remaining pages into Silvia’s hand, and waited till she had come to the end. Then they looked at each other in silence. “I’m going to laugh,” said Peter at length. “No, please don’t,” said Silvia. “If you do I shall cry.” Peter tapped the sheets that lay in her hand.
  • 59. “But it’s gorgeous,” he said. “I should laugh, if I did, not from amusement—though there are amusing things—but from pleasure. Every word in that letter is true; that’s something to be pleased about, and, what’s more, every word in it is right. But the surprise, the wonder of it! There’s a splendour about it!” Silvia shuffled the sheets together, and, giving them back to him, leaned her forehead on her hands. “Ah, haven’t you got any tenderness?” she said. “Don’t you see the bitter pathos of it? Your mother, you know!” “But she says there is nothing pathetic about it,” said he. “And that’s just the most pathetic thing of all!” Silvia said. Peter puzzled over this a moment. He understood Silvia’s feeling well enough, but he understood equally well, and with greater sympathy, the answer (the retort almost) to it. “But if she sees nothing pathetic in the situation, and I quite agree with her, what’s the use of trying to introduce pathos?” he asked. “Pathos painted on—like a varnish—ceases to be pathos at all; it becomes simply sentimentality.” Silvia turned to him like some patient affectionate teacher to a child who pretends only not to know his lessons. “If the absence of love in relationships like these isn’t pathetic,” she said, “love itself is only sentimentality.” Peter again saw precisely what she meant; he knew, too, that what she said was true. But he knew that he, for himself, did not realize it with conviction, with a sense of illumination.... The statement of it was just an instance the more of Silvia’s shining there aloft of his confining cloudland. The thought of that dealt him a stab of envy, and under the hurt of it his spirit snapped and snarled, and retired, so to speak, into its kennel, leaving his mind outside to manage the situation. “Well, then, it’s pathetic,” he said, “but it has been pathetic so long that one has got used to it. I know you’re right, but what you say hasn’t any practical bearing——” “Ah, my dear, but it has,” said she. “It has all the practical bearing. It is up to you, practically, to handle it in hardness in—in a sort of ruthlessness, or you can, recognizing what I say, deal with it tenderly.”
  • 60. “By all means; but the facts aren’t new. Leave me out: let’s consider my father and mother only. There’s the practical side of it. He’s got to be told— at least, I suppose so. There’s no new pathos there. They’ve both been aware of lovelessness for years. If my father takes the wounded, the pathetic pose, it will—it will just be a pose. Frankly, I’m all on my mother’s side. By one big gesture she has explained herself; she has made a living comprehensible reality of herself. The Bradshaws, the railway guide advertisements—good Lord, we know what it has all been about now! There’s flesh and blood in it! I always respect flesh and blood!” “But her way of doing it is an outrage,” said Silvia. “She’s your father’s wife, after all: she’s your mother. Take your mother’s side by all means— we’ve all got to take sides in everything: nobody can be neutral—but take his side in her manner of doing what she has done. Sympathize with him in that! That letter, too—will you show him the letter? The hostility of it, the resentment!” Peter sat still a moment fingering the leaves of the letter. “It’s not so much resentment,” he said, “as repression. She has been hammered back into herself all these years. Oh, I understand her better than you. It had to happen this way. What else was she to do? Could she go to my father and say, ‘If you can’t put some curb on your egoism and vanity, if you continue to be such a bounder (that’s what bounders are) I really shall have to leave you’?” “You want to score off him, Peter,” said she. “That’s the hardness, the ruthlessness. And you aren’t hard, my darling. Who knows that better than I?” “Are you sure I’m not?” he said. She did not answer this directly. “You’ve got to be gentle,” she said. Peter’s fingers closed on the letter, hesitated, and then tore the sheets in half. He tore them across yet again. “Well, he shan’t see the letter,” he said. “It was written to me and I’ve destroyed it. But if, when I tell him, he becomes melodramatic how can I help being what you call ruthless? He’s so vain: you don’t know how vain he is. This will be a brutal outrage, an attempted assassination of his vanity. But it won’t injure it. The dastardly blow will glance aside, and he’ll put an extra bodyguard round his vanity
  • 61. for the future. He’s a ridiculous person, Silvia,” said Peter in a loud, firm voice. Silvia gave a sigh. “Ah, that’s better,” she said, “for you’ve torn the letter up, anyhow, and when you said he was ridiculous, you said it, my dear, as if you were justifying yourself rather than accusing him. Oh, you said it firmly and loudly, but—will you mind if I say this too?—you didn’t say it so spitefully. Now, let’s be practical. You always used to be practical, Peter. When are you going to tell him?” Peter looked at his watch. “That means that if I say that I haven’t made up my mind,” he said, “you will certainly let me know that there is plenty of time to tell him before dinner. You want me to tell him now: that’s where we are. You call me practical: who was ever so practical as you, when it comes to the point?” She did not challenge that, but rather proceeded to justify Peter’s opinion for him. “My dear, you can put off pleasant things if you like,” she said, “because you enjoy the anticipation of them. But where—where is the use of putting off unpleasant things? That only lengthens a beastly anticipation.” “He’ll make a scene,” said Peter. “I hate scenes.” There was nothing to reply to this: it all came under the advisability, which she had already expressed, of not putting off unpleasantnesses. So she made no reply, and soon, for the face of her continued to push him, he got up, still wondering if she would prefer to tell his father herself. How strongly she wanted to do that, and how, more strongly, she refrained from doing it, he had no idea. Her inclination, that which she combated, was simply to go straight to those voluptuous state-rooms; but her will, her convinced sense of what was right, of what was Peter’s own duty and development, kept her silent. “Oh, I am sorry for you,” she said at length, as he turned to go into the house. “But don’t forget to be sorry for him, Peter.” His only answer to that was a just perceptible shrug of his shoulders (comment on the futility of her sympathy), and he walked away across the crackling gravel.
  • 62. Silvia knew how Peter’s mere presence stifled her power of judgment with regard to him. Often and often she had to cling, desperately, to a mental integrity of her own, in order not to be washed away by the mere tide of her devotion to him. Her desire, not only the flesh and the blood of her, but her very spirit, would always have surrendered to him, would have given up herself, whole and complete, to what pleased him, to what made him comfortable, content and happy. But somewhere between these two apexes of physical and spiritual longing there came another peak, a mental and judicial apex, so she framed it to herself, a thing solid and reliable, a kind of bleak umpire that gave inexorable decisions. Already in their fortnight of married life it had several times asserted itself—it was her will, she supposed, clear-eyed and unbribable, which was as distinct from the blindness of love as it was from the abandonment of physical desire. Peter had suggested, for instance, that he should “chuck” his work in the Foreign Office (this was the most notable of these instances) and live, just live, now at Howes, now in London, always with her. They would travel, they would entertain, they would have plenty of interests to keep him busy enough. He had urged, he had argued, he had appealed to her for her mere acquiescence, willing or not, and she had steadily and unshakably refused to give it. Here, to-night, was another test for this umpire of the mind. It would have been infinitely easier for her to tell Mr. Mainwaring herself, and she knew quite convincedly that she would have proved a far more sympathetic breaker of shocking tidings than Peter would be. Peter would now, on his way to the state-rooms, be framing adroit sentences, be schooling his anticipatory impatience at a melodramatic reception of that news by his father into tolerance and gentleness. But she had as little temptation to be intolerant or ungentle, as he had to be the reverse; she would naturally have stood in an attitude which Peter would find it gymnastically difficult to maintain. But he had got to do his best, not to let her do so infinitely better. It took but a moment’s stiffening of herself to baffle any inclination to follow Peter and shoulder his mission for him, and her thoughts went back to Mrs. Mainwaring’s letter and its startling effect (or want of effect) on Peter. That had produced, so she found now when she was no longer under the spell of his presence, a certain incredulous dismay. “You aren’t like that,” she had assured him, but now she found herself saying, “He can’t be like that!” He appeared to have received this intelligence with a savage, or,
  • 63. if not a savage a wholly unpitiful comment. He had seemed, and indeed seemed now, to have applauded this tragic sequel to years of resentful companionship. He had confessed to a desire to laugh (this was the ruthlessness). It might be that the logical result of such years was that Mrs. Mainwaring, given that she retained any independent identity of her own, should have been goaded into this assertion of it. It might, in the ultimate weighing of souls, be better that she should have cut the knot like this, rather than have been strangled by it. It was all very well for Peter to take her side, but to take her side competently included an appreciation of what she had suffered, and what she had failed in. Anyone could form a fair idea of what she, as exhibited now, had suffered by the smallest recognition of what it must have been to be tied to the present occupant of the state-rooms, and the same exhibition showed exactly her tragic failure in allowing herself to be driven into this hermetical compartment, where all that reached her was the contemplation of her escape, as shown by her study of hotels. But Peter turned over all this, which was the root of the matter, as he might turn over the leaves of a dull book, and only saw a dramatic comedy in it, deserving of applause for its fitness, of an exclamation, “Serve him right!” or a laughing, “Well done, mother!” ... You couldn’t deal with people like that; at that rate the whole world would become a relentless machine, always grinding, always seeing others ground, always being diverted at the pitiless revolution of the wheels. Compassion, tenderness, these were the qualities that just saved and redeemed the world from hell, or at least from being a wounding comedy, at which no human person could laugh for fear of crying instead. Silvia got up from the seat where she and Peter had read his mother’s letter, definitely desiring to avoid the conclusion to which her thoughts were leading her. He had wanted to laugh—that was certain, but she must forget that. Probably he had not meant it; it was only incongruousness and surprise (like funny things in church, which would not be in the least funny elsewhere) which had made a spasm.... Peter assuredly was not like that really, and the loyalty of love derided her for supposing it. He was (her heart insisted on that) all that her love adored him for being. The dressing bell had already sumptuously sounded from the central turret, and, still quite ignorant of what had been the result of the disclosure, but conscious of a yearning anxiety to know, she went up to her bedroom. She was not so much anxious to know how Mr. Mainwaring was “taking it”
  • 64. (how he “took it” seemed to matter very little), but how Peter had done his part. Between his dressing-room and her bedroom were a couple of bathrooms, and she heard, with a certain clinging to the usualness of life, splashings and hissings of water coming from one of these. Whatever had happened, there was Peter having his bath, and soon, most likely, he would tap at her door, barefooted (he never would wear slippers as he paddled about between his room and hers) with the blue silk dressing-gown tied with a tasselled cord about his waist. Peter had a wondrous ritual for his bath: he had to immerse himself first of all, and then stand on the mat while he soaped himself from head to foot. Then, still slippery and soapy, in order to get cold and heighten the enjoyment of the next immersion, he turned on more hot taps, and put spoonful after spoonful of verbena salts into the water. Then he got in again, and stewed himself in this fragrant soup. When he was too hot to bear it any longer, he retired into a small waterproof castle at the end of the bath, and turned on all the cold water douches and squirts and syringes. Then, without drying himself at all, he put on the famous blue silk dressing-gown, which had a hood to it, lit a cigarette, and tapped at her door, to ascertain whether he could sit and finish his cigarette there. Silvia, by this time, knew precisely the interpretation of these splashings and hissings of water, and she would hurry up her own dressing, or slow it down, so that she could admit him. Fresh from his scrubbings and soapings, with the glow of the cold water on his skin, he was paganly sensuous in his enjoyment of the physical conditions of the moment, and, sitting by her dressing-table, talked the most amazing nonsense. He dried his feet on the tail of his dressing-gown, he rubbed his hair on the hood of it; there was the scent of soap and verbena and cigarette, and more piercing to her sense than these his firm, smooth skin, the cleansedness and the freshness of him.... At such chattering undress séances she was most of all conscious of him to the exclusion of herself; for whereas his kiss, his caress, united her with him, and she had part in it, when he came in thus, rough-haired, bare-legged, wet-footed, with a smooth shoulder emerging from his dressing-gown, while, enveloped in it, he rubbed himself dry, she felt herself merely a spectator of this beautiful animal. But if he came in now—he might or might not—she knew that to-night she would be involved, so to speak, with him; his character, the essence of him, as exhibited in such account as he might give her of the interview with his father, would come like a cloud or a brightness that would obstruct this
  • 65. purely spectator-like view of him. He would not only be the clean, lithe animal, which, for these few minutes, she could look at without passion, without love, without friendship even, and be absorbed in the mere joy that there should be in this world so young and wild and perfect a creature.... There came his knock, and the usual inquiry, and he entered while her maid, with chaste, averted face, rustled out, not waiting to be dismissed, through the other door. He sat down in the big low chair by her dressing- table. “Oh, the simplest pleasures are so much the best,” he said. “Just washing, you know, just being hungry and sleepy. I never enjoy a play or a book or a joke nearly so much as a bath and food and getting my head well down into the pillow. But I hate sponges. Why should I scrub my nose with a piece of dead seaweed?” Listen as she might, with all the delicacy of divination that love had given to her ear, she could find in his voice no inflection, no hesitation, nor, on the other hand, any glibness (as of a lesson learned and faultlessly repeated) that showed that he was speaking otherwise than completely naturally. The topics of bath and dinner and bed came to his lips with quite spontaneous fluency, as if he had not in this last hour been the bearer to his father of a tragic situation—one that, at least, must wound the vanity which was so predominant a passion in him. Or had Mr. Mainwaring taken it with the same ruthlessness, the same cynical amusement as Peter had appeared to? Silvia could not believe that: he must have been hurt, been astounded. But why, in pity’s name, did not Peter tell her about that interview? He must have known how she longed to be told, whether there was good or bad to tell.... “A revolving brush covered with wash-leather,” continued Peter, “like a small boxing-glove. You would cover it with soap and work it with your foot. But a sponge! Odious in texture, dull in colour, and full of horrible dark holes which probably contain the pincers of defunct crabs and the fins of dead fish.... Oh, by the way, I quite forgot! I did really, darling; I was thinking so much about substitutes for sponges.” Silvia could not doubt the sincerity of this: he had been thinking about sponges; there was the full statement of the case. And with his acknowledgment of that, his mere physical presence, the mere glamour of his radiant animalism, which, after all, was part of his essence and his
  • 66. charm, captured her again, whisking away for the moment all possibility of criticism, or of wishing that he could be other than he was. She knew that her misgivings—they amounted to that—would come flooding back, but just for the moment they were like some remote line of the low tide, lying miles away across shining levels. “Oh, Peter,” she cried, “if you can design a small revolving wash-leather boxing-glove to use for a sponge, I’ll promise to have it made for you. But you must explain just how it’s to work....” She broke off. “And about your father?” she said. “Yes, I was just going to tell you when you interrupted about the sponge- plan,” said he. “By the way, I’ll draw you the revolving boxing-glove. A foot-pedal below—below, mind—the water, so that your foot doesn’t get cold. And, of course, you hold the socket of the boxing-glove—the wrist, so to speak—in your hand, and it goes buzzing round as you work with your foot, and you apply it, well soaped, to your face. No more dead seaweed and lobster claws! My father now!” Peter gathered up his knees in his arms, and sat there nursing them. His dressing-gown had fallen off his shoulder; he looked like some domesticated Satyr, wild with the knowledge of the woodland, but tamed to this sojourn—enforced or voluntary—in human habitations. “I went to him, as you told me to do,” he began. Silvia interrupted him. She wanted him to do himself justice. “No, my dear; you went quite of your own accord,” she said. “I never urged you.” Peter’s eyelids hovered and fell and raised themselves again. Often and often had Silvia noticed that shade of gesture on Nellie’s face; but never, so it struck her, had she seen a man do just that. The gesture seemed to imply acquiescence without consent. “Well, I went anyhow,” he said. “I tapped on his door, and as there was no answer I went in. He was standing in front of that big Italian mirror in— well, in an attitude. He is intending to paint his own portrait, when he has finished that daub of you.” Silvia leaned forward towards him.
  • 67. “Oh, don’t talk like that!” she said. “Don’t be ironical—not that quite: don’t feel ironical.” Peter turned on her a face of mild, injured innocence. “I was telling you the bald facts,” he said. “The balder the better,” said she. “I told him I had read my mother’s letter,” he continued, “and that there was news in it which he had better know at once. I got him to sit down, and I got hold of his hand. And then I told him just the fact that she had gone away.” Peter shifted himself a little further back in his chair and drew his legs more closely towards him, so that his chin rested on the plateau of his knees. “I am not being ironical,” he said. “I am trying to tell you precisely what happened. He made a noise—a gurgle, I think I should call it—and he asked who the damned villain was with whom she had gone. And, to be quite bald, that seemed to me to be unreal. I said that there wasn’t any damned villain, and that she had gone just because she felt she must be free. He wanted to see the letter, and I told him that I had torn it up. Then he began throwing his hair-brushes and dress-clothes into a bag, in order to start off and look for her, and asked me where she was. When I told him that I hadn’t the slightest idea, he accused me of collusion with her. I merely denied that, and said that her letter was as great a surprise to me as it was to him.” Peter threw away the end of his cigarette. “Then he began to guess why she had gone. Now the point of my tearing up my mother’s letter was that he shouldn’t know, wasn’t it, darling?” Silvia heard herself assent. There was a sickness of the heart coming over her, something too subtle for her to diagnose as yet. “So he began to guess,” continued Peter, “and as he tried to guess I was sorry for him—really sorry, you understand?” Silvia’s heart began to thrive again. “Yes, yes; I knew you would be!” she cried. “He soon hit on the reason,” said Peter quietly. “There could only have been one reason, so he thought, and it filled him with the utmost remorse. He had been too big for her, that was what it came to—too great. He had
  • 68. not, in the exaltation of his art—this is quite what he said—remembered the limitations of—of the rest of us. She had fainted before the furnace of his genius. It was all his fault: he hadn’t made allowance for the prodigious strain on her—for the effects, cumulative no doubt, of the high pressure. He strode about the room, he knocked over a chair——” Some fierce antagonism to his narrative blazed up in Silvia. She had wanted the facts, and here they were, but she had not allowed for the baldness of their presentation, though she had asked for it. “Ah, don’t talk like that, Peter,” she said. “You’re not a newspaper reporter.” Peter gave no reply at all. There he sat with his chin on his knees, quite silent.... If Silvia chose to speak to him like that it was clear that she must either go on or draw back; anyhow, the next word was with her. But all the time that he thus tacitly insisted on his rights, resenting what she had said, there was within him some little focus of light breaking through from her sunlit altitudes that illumined and justified her protest. Good Lord, wasn’t she right? Wasn’t his sentiment towards his father immeasurably ignoble compared to the comprehension of her love? And that very fact—his own unavowable condemnation of himself, that is to say—irritated him. If she was like that there was no use in his continuing his story. Silvia spoke first. Humanly, she could not bear this silence in which Peter seemed to mock her, but divinely she must be ever so humble.... Humble? How love sanctified humility and transformed it into an ineffable pride. She pushed back her chair and knelt by his. She longed to unclasp the brown lean hands that enclosed him in himself and make them embrace her also. But that might annoy Peter: there was a suggestion of “claiming” him about it. She did not want to claim him. “I don’t know why I spoke like that,” she said. “I asked you what happened, and you are telling me. Will you forgive me and go on?” Peter had never seemed so remote from her as then. In the frantic telegraphy of her spirit, which seemed to be sending all the love that the waves of ether would bear, there came no response from him, in spite of his answer. “I never heard such nonsense,” he said. “We should be a pretty pair if we had to forgive. How silly—you know it—to ask me to forgive you.” “Show you do, by going on,” she said.
  • 69. It was clear to him that what she wanted was to know not his father’s part in this interview, but his own. Whether she liked it or not, he was going to be perfectly honest about it. “When he knocked over a chair and strode about,” he repeated, “and found out the reason for my mother’s going away, I began to be less sorry for him. He enjoyed himself: it was all a tribute to his impossible greatness. From then onwards I acted, because he was acting. The alternative was to tell him that my mother simply found his egoism intolerable. That wouldn’t have done any good, so I agreed with him: that was the best thing to do. He is in despair, a rather luxurious despair. I had either to explode that or let him enjoy it. So it was no use being sorry for him any longer.” Silvia broke out again; it was her love for Peter that spoke. “My dear, you ought to have been a million times sorrier,” she cried. “If he had been just simply broken-hearted about it, it would have been so much better. Can’t you see that? Can you help feeling it?” She was shedding the gleam on him. “I know what you mean,” he said. “But I’m telling you what happened. I was less sorry for him when he began to console himself. I suppose I’m made like that.” Silvia bit her lip. “Indeed you are not,” she said. “You’re making yourself out to be hard and unloving.” At the moment the clang of the dinner-bell from the turret just above Silvia’s room broke in.... The whole neighbourhood must know when the family at Howes were warned that it was time to dress, and that three- quarters of an hour later it was time to dine. Peter, on the first evenings he had spent here with Silvia, had asked whether, like a Court Circular, such publicity need be given to their domestic affairs; but Silvia, confessing herself sentimental, had told him that her father had delighted in the installation of that sonorous announcement. The brazen proclamation “hurt” nobody, and “Daddy liked it.”... Certainly it served a purpose now, and Peter jumped up. “Lord, there’s dinner!” he said. “And I haven’t begun to dress. My father, by the way, wants to dine upstairs. Will you tell them, as you are so much more advanced than I, to send up his dinner? I must fly.” Peter stood for a moment looking at her. If a situation between them had not actually
  • 70. laid hold of them, it had thrown a shadow over them, and he wanted to get out into sunlight again. “Ah, you darling!” he said with a blend of envy and of admiration somewhere gushing up. Envy at her immense nobility—he could think of no other word for it—and admiration at that shrine of love which rose from the ground of her heart. It was so beautiful an edifice: he despaired of being worthy of it, and at times, so he confessed to himself, he wearied of its white stainless purity.... Somehow this evening there seemed to have opened a little crack on its soaring vault, which he must mend somehow. “Give me a kiss, then,” he said.
  • 71. CHAPTER XI Peter, though he often hung a veil over the real workings and processes of his mind for the benefit and admiration of others, before whom he was anxious to present a charming appearance, was honest with himself, and found, during the next fortnight, without any desire to dissimulate, that he was distinctly grateful to Silvia’s insistence that he should not resign his place in the Foreign Office, for, in the present conditions and environments at Howes, it was certainly preferable to spend the solidity of the day in London rather than enjoy uninterrupted leisure at home. Even then the evenings were full of crashes and crises and intolerable ludicrousness.... His father, who still majestically occupied the state-rooms (and showed no indications of vacating them), moved along peaks and summits of the ridiculous, which his son really believed had never before been trodden by foot of man. That he was enjoying himself immensely Peter made no doubt whatever, living as he did on the heights of egoism, and free to indulge in the most extravagant exhibition of it. His standard (victoriously raised), his principle, his determination (announced with magnificent gestures once if not more, during the evening) was that he would remain rock-like and immovable, fulfilling the destiny of his own supreme will, whatever bombs Fate might choose to drop on him. That his whole soul was bitter with remorse for his failings and failures he did not deny. He should not have isolated himself, as he had done, in the supernal realms of Art; he should have remembered that he was a man as well as an artist, and had a wife as well as the celestial mistress of his soul. He ought to have been kinder, more tender, more indulgent to the frailty and the weakness of his Carissima. But remorse (so waved his standard), if it was the genuine article, must express itself not in idle repinings, but in a manful facing of the consequences of past error. His remorse (the right kind of remorse) did not weaken, but strengthened a man to go forward. He must not lose touch with the joy of life; he must not get from the severe spanking that remorse gave him only a smarting and a humiliation of the flesh. He must draw the lesson from his punishment, and proceed more tenderly but not less sublimely than before....
  • 72. It must not be supposed that Mr. Mainwaring used such expressions as “spanking” in actual speech, or that the ironical account of his sublimity, as given above, was verbally his. But such, anyhow, was the manner in which these great tirades, delivered to Peter when he went up to see his father on his daily arrival at Howes an hour or so before dinner, impressed themselves on his mind. Usually there was a note for him on the table in the hall, which ran something like this: “My Peter,—I am very low and despondent to-night, and I do not know if I can face a sociable evening. Come up to see me, my dear, for you are the only link which is left to me of those happy—far too happy—years, and see if your sweet spirit will not, like David playing before Saul, exorcise the demons of remorse and regret which shriek and gibber round the head of your unhappy father. I have tried so hard—ah, so hard—all day not to make myself a burden and a shadow to your dear ones, but I fear I have acquitted myself very ill. Come and cheer me up, Peter.” Peter, to do him justice, always went, and in the majesty of egoism, his father, without any encouragement at all, would talk himself into a splendid courage. At whatever cost to himself, at whatever effort from worn and debilitated nerve-strings, he would show that there was some music yet left in his. He would twang his mental guitar, and if the frayed string snapped— well, his lawyer would know that his affairs were in order.... Then, sooner or later, to Peter’s great relief, the sonorous dressing-bell would ring, and he could go and have his bath. As likely as not, before he definitely quitted the room, his father would allude to the magnificent 1896 port which formed so admirable a feature in the cellars of Howes. Usually after the bath he went in to see Silvia, but, for some reason or other, the spontaneous nonsense of these interviews had wilted and withered. Silvia, so it seemed to him, held herself in reserve, waiting for something from him. Peter would give an account of his day, of his talk with his father, and still Silvia seemed to wait. She was overbrimming with all that she ever had for him, but, to his perception, what she waited for was for him to turn the winch of the sluice. Once there had been a really outrageous scene with his father, in which, after tears, Mr. Mainwaring had slid from his chair with a groan, and lay, an ignoble heap, upon the floor. Peter on this occasion had given Silvia a perfectly colourless précis of the degrading exhibition, and had endorsed it,
  • 73. brought collateral evidence to bear on its nature by the production of one of the notes which usually awaited him on his return from town. He had done that in some sort of self-justification: Silvia could not fail to realize how trying, from their very unreality, such scenes were for him, and he gave her also every evening a very respectable specimen of his patience with his father. And yet he felt that Silvia was not waiting for that; it was not how he behaved, how patient and cordial he schooled himself to be, that she waited for. He was patient, he was cordial, and though she often gave him a little sympathetic and appreciative word for his reward, it was no more than a sugar-plum to a child, something to keep it quiet. What she wanted, what she longed for the evidence of, was an internal loving driving force which turned the wheels of the machinery of his impeccable conduct, and that he had not got for her. He spun the wheels with a clever finger from outside. But usually these wheels went round merrily enough. He reported his father’s despondence; he, ever so lightly, alluded to the fact that he had cheered him up, and his estimate was justified, for Mr. Mainwaring, on the crashing of the dinner-bell in the turret, would sometimes announce his progress from the state-rooms by a jubilant yodelling, and would remain for the greater part of dinner in a state of high elation. True, he would have a spasm now and then: if he happened to have his attention called to Mrs. Wardour’s pearls, he might for a brief dramatic moment cover his eyes and say in a choked voice: “My Carissima had some wonderful pearls”; but then, true to his manly determination, he would dismiss the miserable association and become master of his soul again. Peter usually had a second dose of his father’s Promethean attitude later in the evening, after Silvia and her mother had gone upstairs. “Your treasure, your pearl of great price, your angel!” he would ejaculate. “Her sweet pity, her divine compassion! It is she—she and you— who reconcile me to life. But I must not bask too long in that healing effulgence. I must get back to London; I must reinstate myself in my desolate house, and face it all, face it all. I must stand on my own feet again, poor sordid cripple that I am.” Then perhaps, if quite overcome, he would bury his face in his hands, but much more usually he would stand up, throw out his chest, breathe deeply, and draw himself up to the last half- inch of his considerable stature.
  • 74. “Work!” he said. “Work is the tonic that God puts in the reach of all of us. Remember that, my Peter, if grief and sorrow ever visit you. But then you have by your side the sweetest, the most sympathetic woman ever sent to enlighten the gloom of this transitory world. So had I, by God, so had I, and I did not recognize her preciousness and her fragility.... Enough! Silvia! Did you notice her exquisite love towards me at dinner to-day, when for a moment the sight of Mrs. Wardour’s pearls unmanned me?” Peter on this occasion was lashed to the extremity of irritation. “I don’t think I did,” he said. “I only remember that she instantly asked you if you would have some more pheasant.” He tried to do better than that. Certainly there was no use in saying that sort of thing. “But she looked at you, father,” he added hastily. “You felt what she was feeling. Was that it?” His father clasped his hands. “A divine beam came to me,” he said. “A message of consolation. It made me live again. Surely you saw its effect on me?” Peter, at such moments, longed for his wet woods. He wanted to be by himself, or, at any rate, with someone who could understand and enjoy this stupendous farce. If only Nellie, for instance, had been sitting there with him, how would their eyes have telegraphed their mental ecstasy. Silvia, at this same moment, would not have served the purpose; she might see how ridiculous his father was being, but below her perception of that, which might easily have made her telegraph and smile to him, there would have been that huge, unspeakable tenderness which, when you wanted an answering perception of farce, would have spoiled it all. That universal embracing compassion required salting. Before now she had seen, and communicated to him, her sense of his father’s absurdities, but now, when he turned trouble into an empty arena for his posturing, her sense of comedy completely failed her. Or, if she still possessed it, Peter could not get at it. With a flare of intuition he guessed that it might be unlocked to him, if only he could use the right key to it. But the key was compassion, and it was he for whom she waited to thrust it into the wards. If only he loved they could laugh at anything together; without that the gate was locked.
  • 75. Well, if it was locked, he would enjoy his imperfect vision of what lay within. “Yes, I saw its effect on you,” he said, trying to imagine that Nellie was here, enthralled and wide-eyed, “You amused us all very much immediately afterwards by making that lovely sea-sick passenger out of an orange. Perfectly screaming!” His father thrust his hands through his hair; it stood up like some glorious grey mane. “Yes, yes,” he said, “I made an effort. I won’t, no, my Peter, I will not lose sight of the dear gaieties of life. God knows what it costs me! Even after a little thing like that I was more than ever plunged in the gulf of despondency. I know how wrong I am. I must never relax my efforts; I mustn’t give myself time to think. Work and laughter—those divine twins.” He poured himself out a glass of whisky and soda, and chose a cigar with proper care. “A word or two on practical affairs,” he said, “before I go to my lonely and wakeful bed. You will be here, I understand, till early in December. By then I trust (I insist, indeed, on thus trusting) that I shall have schooled myself to face the desolation of my home (what once was home) again. May I, do you think, ask to remain here till then? I look upon your beautiful Howes as my hospital. Soon, still maimed, still limping, still in the blue uniform of pain, I know that I must, indeed I insist on it, face the world again and make the best of my shattered existence. But till then? Silvia, whom I consulted with regard to this matter, told me that you were the master of Howes, and suggested my speaking to you about it.” Peter saw an opportunity. His father, it is true, was an odious infliction of an evening, but there was something to be gained by his own eager tolerance of that, which quite outweighed the inconvenience. But he must do more than tolerate; he must welcome; and Silvia—here was the point— must know how splendidly he had risen to it. Before he answered he made himself remember what the intonation of cordiality sounded like. “But that is perfectly charming of you,” he said. “It’s lovely that the suggestion came from yourself. She and I may be away for a day or two in November——” Peter did not quite know what arrangement he was to suggest about such days when he and Silvia would be away, for instance, on their visit to
  • 76. Nellie. He was spared the trouble of formulating one by his father, who gave a great gesticulation, admirably expressive of courage. “I will go home—home for those days,” he said. “I will, with set teeth and firm mouth, begin to grow accustomed to my desolation and loneliness. I will learn to bear it, taking in long draughts the inestimable tonic of work. Peter, Peter”—and the voice shook—“when will my Carissima come back to me?” He was unmanned only for a moment, and his mastery of himself returned to him. “Was ever a stricken man so blessed by the love of his children?” he exclaimed. “God bless you, my Peter. You are going to bed?” The abruptness of this benediction convinced Peter that his father had got what he wanted and had no more use for him that night, and he went along the corridor to his room and Silvia’s. His first impulse was to tell her how cordially, for his part, he had welcomed his father’s suggestion; the second and wiser one was to say nothing about it. Mr. Mainwaring was sure to make the most of it to her; he might even attribute to it that force from inside which turned the wheels. Yes, Silvia should learn about it like that. He let himself very quietly into his room, and undressed and went to bed without going in to say good night to her. If he went in to see her, it was more than likely that she would ask him whether his father had alluded to the question of his remaining with them, and he wanted the information concerning that to be conveyed to her by one who would give him, Peter felt sure, a florid testimonial for cordiality. He had passed, moreover, a monotonous and fatiguing evening, and wanted not to talk at all, but to sleep. His father had been slightly more dreadful than usual, Mrs. Wardour had more than ever been non-existent, and Silvia, so it struck him, had been waiting, had been watching him, not, it need hardly be said, with fixed eye or stealthy glances, but with some steady psychical alertness that was incessantly poised on him. Without looking at him, without any talking to him or talking at him, he had felt all evening—this, perhaps, had been the most fatiguing part of it—that she had scarcely been conscious of anyone else but him. Though her eyes were on the cards, and she ruefully bemoaned that the goddess of piquet, whom she jointly invoked with Peter’s father, had been so niggardly in her favours towards herself, it had
  • 77. been no more than an automaton that was thus victimized to the extent of three lost games, including a rubicon. Peter, as he curled himself up in bed, let his mind stray drowsily over such details of the evening, coming back always to this impression of Silvia’s watching him. Whenever he spoke to her of his father she watched him—seldom with her eyes—in just that manner. By aid of his quick perception, that felt rather than reasoned, Peter had, he was sure, arrived at what she watched for then. She watched for some token, she listened for some inflection that indicated tenderness, sympathy, affection towards his father. She could not have been watching for any such token as that for herself, for he gave her those; she knew they were hers. But he had never felt more certain about anything in these dim, vague regions of sentiment and desire than that she wanted something more than that which he gave her, and a certain impatience gained on him. What, after all, had been her own first words to him when he asked her to marry him? Had not her face flamed with the light of the beacon that welcomed him as she whispered that all she asked was to be allowed to love him? At the time that had seemed to him a divine intuition, one that, in a word, precisely defined her way of love and his. There came at that door of his bedroom which led to her room the lightest, most barely audible of touches; he was scarcely sure whether he had heard it or not. But he did not reply, for either it was imaginary, and needed no answer, or it was Silvia come to see whether he was in his room yet. In that case, even more, an answer must be withheld, for after this evening of strain and high pressure all he wanted was to be let alone and to go to sleep. But underneath his eyelids, not quite closed, he watched the door which was opposite his bed and was dimly visible in the glimmer of starshine that came in through the open and uncurtained window. Round the edge of the door, though he had heard no click of a turned handle, there came a thin “L” of light, which broadened until, in the shaft of it, appeared Silvia. She held a lighted candle, which she screened from his bed with her hand, the fingers of which, close to the flame, were of a warm transparent crimson. Apparently his clothes, tumbled together on a chair, first caught her notice, and from them she looked straight towards the bed. Her face was vividly illuminated, and when she saw him lying there with shut eyes, some radiant, ineffable tenderness came like dawn over it. Never had he seen so selfless and wonderful a beam; she might have been some
  • 78. discarnate spirit permitted to look upon him who had been the love of her earthly heart. That, then, was how she regarded him when she thought she was unobserved by him; he meant that to her. Next moment, round the half- open door, the light narrowed and disappeared, and he was left again in the glimmering dusk. Never had he seen with half such certainty and directness what Silvia was. She had thought he was asleep, and so she could let free her very soul. Neither by day nor night had she come to him quite like that; all other emotions, amusement, interest, sympathy, desire, passion even, had concealed rather than revealed her. They had been webs and veils across the sanctuary, illumined, indeed, by the light that burned there, but still hiding it. Now for one moment Peter had seen her with those veils drawn aside, the holy place of her, and her love was the light of it. He was sitting next afternoon in his room at the Foreign Office, rather harassed by the necessity of being polite to everybody. The clerk senior to him in his department was on leave, and it happened that an extra King’s messenger had to be sent off to Rome, carrying a new cipher. That was a perfectly usual incident in Peter’s routine, but this messenger was fresh to his job, and had been in and out of the office all day, fussy and pompous, wishing to be assured that he had got reserved compartments and a private cabin. There was a strike on the French railways going on, and Peter had told him that it might be impossible to secure a compartment farther than Paris, but all that could be done had been done, and, anyhow, he would find a seat reserved for him. Usually Peter rather enjoyed applying soothing ointments to agitated people, and his skill as a manipulator of pompous and fussy persons was so effective that by common consent (he quite agreeing) tiresome officials were often turned on to him for emollient manipulation. But to-day the telephonings and the interruptions and the pomposity and the prime necessity of remaining dulcetly apologetic for inconveniences which were wholly out of his control had got on his nerves, and when finally, in answer to inquiries, it had been determined that the King’s messenger had better, in order to secure a journey probably unvexed by strikes, go round by Southampton and Havre, Peter had been treated to some very acid talk. Of course, the man was an ass, no one knew that better than he, and it was ludicrous to be infuriated by an ass. About six then, that afternoon, Peter had done all that patience and polite inquiries from French station-masters could do for the ass, and with
  • 79. undiminished civility he had wished him a pleasant journey. In half an hour, or, if he chose, now, since there was nothing more that could detain him, he could telephone for his car and slide down to Howes. He did not in the least look forward to his evening there; it would assuredly be an evening of as high a pressure as the day had been. His father would certainly be voluble with blessings and gratitude, and Peter hated the prospect of these benedictions. Installed as Mr. Mainwaring now was for a couple of months more, he would surely develop the idea which he had before now outlined, when he assured Peter that during his daily absences in London he himself would act as his vice-regent. He had already caused the luncheon hour to be changed in order that he might get an extra half-hour of work into the morning; already he had got the estate carpenter to “knock him up” an immense frame in which he could see his second cartoon, now dismally approaching completion, more satisfactorily displayed. And then Peter thought of that short candle-lit glimpse last night, when Silvia had looked into his room. For one moment the remembrance of that magnetically beckoned him; the next, as by some inexplicable reversal, the needle of that true compass swung round and pointed in the opposite direction. It no longer gave him his course back to Howes; it steadily pointed away from Howes. But even as he told himself how inexplicable that was, his subconscious self gave a convincing explanation of it. To hurry back to Silvia and her watch of love, to feel that there were veils which only he could draw aside, but which, when drawn aside by God knew what aspirations towards a light he did not comprehend, would reveal to him again the glory of her sanctuary, was a task for saints and lovers. He would rise to it in time, he would learn to be worthy of an ideal that somehow, in spite of its white heat, had the chill of asceticism frosting it; but just now he longed for ordinary, unreflective, unstruggling human gaiety. She—Silvia—lived naturally on those heights, just as his father lived in the cloud—or the shroud, maybe—of his own inimitable egoism. He was tidying his table, intending to ring up very soon for his motor to take him back to Howes. If he started in half an hour he would have time to see his father before dressing, and to talk to Silvia between bath and dinner. Then he changed his mind and determined not to ring for his motor at all. Instead he would walk back across the park—no, not across the park, but up Whitehall, and so by streets all the way to Piccadilly. He would have time
  • 80. to get a cup of tea at home and start from there immediately afterwards. The rather longer route by the streets was infinitely preferable. There would be crowds of ordinary human beings all the way, people not monstrous on the one hand, so far as he knew, from swollen egoism, nor irradiated by idealisms which made you pant in a rarefied atmosphere. There would be just masses of people, people gay, people sulky, ugly people, pretty people, but above all ordinary people. At the moment when his tidying was complete, and his table ready for his next day’s work, the telephone on his table tinkled. He resigned himself to more inquiries from the incomparable ass, but they could not last long, for his train left Waterloo within a manageable number of minutes. But in answer to his intimation that it was indeed he who waited at the end of the wire, there did not come the voice which he had listened to so often that day, but one quite other and equally recognizable. “Nellie?” he said. “Yes, my dear. How lucky I am to catch you. You’re in town, then?” “At the moment,” said he. “I’m going back to Howes in half an hour.” “Oh, what a pity! You won’t be in town to-night, then?” “Why?” asked Peter. “Only that Philip and I were going to the play, and Philip’s got a cold and thinks it wiser not to go out. I thought perhaps—just a lovely off- chance—that you might come instead. Oh, do, Peter.” “Hold on. Wait half a minute,” said he. He put the receiver down on the table, seating himself on the edge of it. Here in excelsis was precisely what he longed for. Dinner, a theatre, a talk, all with Nellie, who represented to him (though in excelsis) the ideal epitome of the world of humanity. He had thought a moment before, with the sense of anticipating a “break,” the mere walk through crowded streets. She would in this programme give him all that intimately, she would give also the sense of intimate friendship without effort. They would jabber and enjoy—— He took up the receiver again. “Yes, all quite easy,” he said. “It’s late already, and when it’s late and I can’t get down there, I can always sleep in town. Silvia and I settled that when I began work again in this doleful office.”
  • 81. Nellie appeared to laugh at that. “Silvia evidently spoils you,” she said. “But it’s too lovely to catch you like this. Will you dine with me at the Ritz? Seven? The play—can’t remember what it is—begins at eight. So we shan’t have to hurry, and can sit with our elbows on the table for a bit and talk.” “Sit with what?” asked he. “Elbows on the table,” said Nellie with elaborate distinctness. “No hurry —talk.” This time he laughed. “Oh, don’t let’s go to the Ritz,” he said. “Come and have elbows at my great house. I’ll go back there now and order dinner. It’ll probably be beastly, but it’s more private. Shall we do that?” “Much nicer,” said Nellie. “How are you, Peter? Oh, I can ask that afterwards. Seven, then. Wardour House.” “Yes. Give condolences to Philip. Not congratulations, mind.” Peter hung up the receiver, and then took it off again at once in order not to give himself time to think. There would be clamour and argument if he thought, and he wanted nothing of that sort. Ten minutes afterwards he left the office, having telephoned to the Jackdaw that he was detained here and would be obliged to sleep in London. Two months had passed since Nellie and he had met, but whatever frontier-change of limitation or expansion had been decreed for each severally since then, their meeting to-night had the power to put such aside, and they hailed each other without the embarrassment of altered circumstances. Their compasses were rigidly in accord, and as the excellent impromptu meal proceeded the talk sailed towards northern lights, in the direction of their steadfast needles. Soon they were sitting (at the elbow stage) with their coffee and cigarettes, with a quiet quarter of an hour in front of them before they need start. “Motor at ten minutes to eight,” said Peter to the servant, glancing at the clock. “Tell me when it comes round.” He shifted his chair a little sideways towards her. “Oh, this is jolly,” he said, “for we’ve gone on just where we left off. You’re just the same. It’s two months, you know, since I set eyes on you.
  • 82. Do say you’ve missed me.” “What else did you expect?” said she. “Marriage isn’t—— Oh, Peter, what’s the name of that river?” “Thames?” asked Peter. “No, the forgetting one—Lethe. Because I’m married to Philip I don’t forget—other people. But tell me, has Silvia been giving you Lethe to drink instead of early morning tea?” “Not a drop. She’s given me everything else in the world.” Nellie still had that habit of plaiting her fingers together. “You ought to be very grateful to me,” she said. “It was I, after all, one night at my mother’s flat, do you remember?” “I was Jacob that night,” remarked Peter. Nellie frowned. “Don’t tell me how,” she said. “I want to see if we think side by side still. Ah, I’ve got it! Philip was Esau—isn’t that clever?—and I told him I was tired, and so you supplanted him.” “Right. Get on,” said Peter. “Yes, about your gratitude. It was that night that I told you to ask Silvia to marry you. Didn’t I?” “Yes. Thank you, dear Mrs. Beaumont,” said Peter effusively. “So good of you to tell me.” “It was a good idea, wasn’t it?” Nellie’s mind stiffened itself to “attention” at that moment. Before, it had been standing very much at ease. “The best idea in the world,” he said. “I’m awfully glad,” said she. “What you say, too, makes it all the more delightful of you to stop up in town to-night, instead of going back to her.” Though up till now they had fitted into each other with all the old familiar smoothness, it appeared now, when they got near, in their conversation, to what had happened to each of them (not, so he still felt, altering them, but putting them into new cases) that there was fresh ground to be broken; hitherto they had only picked their way over the old ground. Nellie felt this even more imperatively than he. They had got to run the plough (so why not at once on this admirable opportunity?) through the
  • 83. unturned land.... Peter’s servant had already appeared in the doorway, announcing the motor, and she had noticed that, but Peter had not. She concluded from that, that he, easy as their intercourse had up till now been, was feeling some pre-occupation. His hesitation in answering her last acknowledgment of his amiability in remaining in town instead of going back to Howes, confirmed that impression. Then, before the pause was unduly prolonged, so as to amount to embarrassment, she put her word in again. “I appreciate that,” she said, “because it shows that the new ties haven’t demolished the old. And on my side I admit, far more definitely than you, that if my poor Philip must have a cold, I am glad—ever so glad—it visited him to-night, so as to give me an evening with you.” She swept her plate and coffee-cup aside, to make room for an advance of the elbows. “Oh, my dear, I have missed you,” she said. “Naturally, however perfectly Philip is himself, he couldn’t be you. My mind—perhaps you haven’t noticed it—has wonderfully improved these last months—I am learning Italian, and we read Dante—but it needs just a little holiday. And I’ve found out such a lot of things about Philip, and all of them are good, worse luck.” Peter looked up at her with that liquid seriousness of eye which to her meant that he was walking in the wet woods. “Oh, poor thing,” he said. For some reason which she did not choose to investigate, Nellie found that remark immensely encouraging. Certainly, a few minutes ago, she had tried to provoke him to talk—really talk, but the ironical perfection of his condolence, which, so she felt, saw all round what she was saying, made her more than acquiesce in his listening instead of talking. She felt sure that this beloved Peter understood—— “I knew you would sympathize,” she said; “but there’s my tragic prosperity. My Philip isn’t lazy or spiteful and inconsiderate or selfish, or bad-tempered or greedy or—or anything at all, except that he knows so much about birds. He has taught me a lot, and he’s quite absolutely devoted to me. He never liked anybody so much as me. But do you know, darling, to a woman, at any rate, having a good, nice man quite devoted to her, as far
  • 84. as his affections go, gives her, once in a way, a little sense of strain. She has to find her hymn-book and sing.” “I’ll lend you mine,” said Peter, speaking without thought, but only by instinct. “Thanks. When will you want it back? No; I won’t borrow it. But the fact is, that an undilutedly good man wants something to make him fizz. You must have humour or a vile temper or cynicism or greediness, or something, to make you drinkable.... My dear, what am I saying?” The clock on the mantelpiece struck the hour at which the curtain of their play rose; but the chimes, eight sonorous thumps, preceded by the quarters, penetrated Peter’s brain no more than the announcement of the motor ten minutes ago had done. “You’re talking awfully good sense,” he said. “At any rate, you’re talking a language I can understand. You always did; we quarrelled and wrangled, but we were on the same plane.” “So we are now, thank heaven,” said she. “It’s time you gave me some news, you know.” Whatever pre-occupation it was that held Peter, he seemed to shake himself free of it. “Yes, I’ve got news all right,” he said. “Domestic tragedy.” “Oh, my dear, what?” asked she. “Nothing awful?” He seemed to know for certain that she was figuring in her mind something about himself and Silvia. So, in the upshot, the sequel, the development, he was. But he tested her, so to speak, over the domestic tragedy itself. “My mother has run away from home,” he began. Nellie did not laugh. She only bit her tongue with firm purpose. “Dear Peter!” she said, when she released it. “She has simply gone,” he said. “Round about ten days ago, when father arrived to study his first cartoon, with a view to the rest of the series—Mrs. Wardour bought it, by the way—gracious me, what a lot we have got to talk about.” “Never mind the cartoon,” said Nellie with thrilled interest. “Get on with the tragedy.”
  • 85. Quite uncontrollably Peter’s mouth began to lengthen itself. He did not quite smile, but the promise of a smile was there. “Tragedy, then,” he said. “My mother sent me a long—oh, such a priceless letter, to say that when my father came home again—his home, I mean—he would find she had gone.” The Dryad, the gay conscienceless Nellie, could not, in spite of her improved mind, quite contain herself. “But your mother?” she asked. “At her age? How absolutely wonderful of her! Do you know who he is?” Peter tried not to laugh, and completely failed in that dutiful endeavour. She could but follow his lead, and the two, drawing psychically nearer to each other every moment, abandoned themselves, just for natural relief, to this irrepressible mirth. “You are such a damned fool, Nellie,” he said at length. “Do listen: don’t be funny. It’s quite different.” “ ’Pologies,” said she, rather shakily. “It wasn’t anything so romantic, but it was just as human,” said Peter. “You know how my mother was hammered into herself—that phrase came in her letter, by the way: it’s not original.” “But I never guessed there was anything to hammer,” said Nellie. “Nor did I; at least, I only half guessed. But there was. A breaking point came, and she couldn’t stick my father any longer. She has just gone away. Do you remember how she used always to be looking up hotels in railway guides?” “I remember that most of all,” said she. “Well?” “She’s gone to one of them. She’s just gone away to be free, not to lead somebody else’s life any more. When she has got a good breath of air, she may, apparently, come back. But she doesn’t promise.” Nellie had grown quite serious again. “That’s even more wonderful of her,” she said. “She just went away because she wanted to be herself. My dear, what a mother! And waiting till you were married! And your father? Go on.” This time Peter’s mouth strayed beyond the limits of mere reflective meditation, and smiled broadly.
  • 86. “He has discovered, to his complete satisfaction, why she left him,” he said. “He knows—as if Gabriel had told him—that his tremendous personality, his devotion to Art, all that sort of thing, was too much for her. He reproaches himself bitterly—and oh, my dear, how he enjoys it—with having failed to realize the frailty—not moral—the weakness, the ordinariness of other people. She was scorched in his magnificent flames, and escaped from that furnace with her life.” “But how lovely for him!” said Nellie. “Lovely for her, too. But why tragedy? You said it was a tragedy?” His whole body gave a jubilant jerk. If he had been standing up he must have jumped. “Ah, you do see that, don’t you?” he cried. “I just rejoice in her! At least, I would——” Nellie divined perfectly well that “if Silvia understood” really completed the sentence. But if Peter wished, for the present anyhow, to leave that unspoken, loyalty to their comradeship prevented her from suggesting it. Another motive, not less potent than that, dictated her silence on the point, for she infinitely preferred that he should volunteer some such information concerning himself and Silvia than that she should give away her knowledge of it. Certainly she longed to know in what real relation he and Silvia stood to each other, but it would be a tactical error (tactical was too businesslike) to let him know that his incomplete sentence gave her so certain a hint. “I see,” she said quickly. “You would rejoice in her if it wasn’t for your father.” Until the two ultimate words of that were spoken Peter’s eyes had been bright and expectant. He evidently waited for the termination which she had refused to utter. When her sentence was complete she saw, unmistakably again, that his eyes accepted and acquiesced in her conclusion. “Quite,” he said in a level voice. “So for the present my father is consumed with remorse, and is occupying the state-rooms—you’ve never seen them; gorgeous tapestry and Lincrusta Walton ceilings—till we come up to town. He is painting away at the series of cartoons.” Peter poured himself out a second cup of coffee from the tray that had been left between them half an hour or more before.
  • 87. “Aunt Joanna!” he said. “You never heard such a plot or saw such a person. She’s my mother-in-law’s sister, you know. She’s ‘got at’ my father, there’s no doubt of it, and she’s secured all the cartoons by bribery and corruption, instead of their being painted for the gallery—the Art Gallery, I should say—at Howes. Aunt Eleanor—she’s my father-in-law’s brother’s wife—has secured the sketches for the cartoons. They’ve been to Howes once, but my father quite dominated them. That was before the crash, so you may judge how much more, with that added string of tragedy to his bow, he would dominate them now. They are more priceless than words can say. There will be a family gathering at Christmas, I understand. Nellie, do come. We would have such a gorgeous time if you were there. We would sit quiet and notice and drink in, and then we would sit over the fire together when Uncle John and Uncle Abe——” “Uncle Abe?” asked Nellie in an awed voice. “Yes. Sir Abel Darley, K.B.E., husband to Aunt Joanna. Don’t interrupt. When Uncle John and Uncle Abe and Aunt Eleanor and Aunt Joanna have gone, not staggering at all, but ‘full up,’ to bed, we would have such holy convocations about them.” Nellie had inferred a little more information about Silvia by this time, but what occupied her most was not what she was inferring about anybody. It was quite enough for her to realize that for the duration, anyhow, of the first act of the play which they had meant to see she was in the old full enjoyment of Peter again. They had stepped back into the candour and closeness of their friendship, and though he had not, as she had, confessed that he was having a holiday, it was transparently clear that this was the case. But just there the candour was clouded; she guessed that, even as she was having a holiday from Philip (God bless him), so Peter was having a holiday from Silvia. Only—here was the difference—he did not or would not own up to that. Even in the projected scheme of Christmas-hilariousness at the uncles and aunts, Silvia did not appear as ever so faintly ridiculous, or as ever so faintly partaking in the midnight merriment. Throughout their talk Peter had kept her hermetically apart. Once or twice, Nellie conjectured, he had pointedly enough refrained from introducing her. She could visualize the rest of them down at Howes, but the part that to Peter Silvia played was mysteriously shrouded. When you were laughing at everybody all round, why should you except one person from the compliment of amused criticism? It was clear that Silvia had no applause
  • 88. for the comedy of Peter’s parents, for he had so cordially welcomed her— Nellie’s—appreciation of it. What, then, was Silvia’s line, what was her relation, above all, to Peter? She decided not to burn all her boats, but to set fire to just a little one. “Won’t Silvia enjoy them too?” she asked. “Can’t tell,” said Peter. If there was a lapse of loyalty there, if, in a minor degree, there was a sense conveyed of disappointment, though of accepting that disappointment without comment, Nellie decided that Peter was not intending to enlarge on it. She still (after that small burned boat) clung to the chance of Peter’s volunteering information, but clearly she would not get that just now; and another heavy booming of quarters from the clock gave her an excellent opportunity of abandoning that which, after all, had never been a discussion on her own initiative. “Good gracious, it’s a quarter to nine,” she said. “You wretch, Peter! We’ve missed one act, if not two.” “Let’s miss them all,” he said, “and have an evening.” That made her pause, but only for a moment. Peter had consistently shied away from that one topic she wanted to hear about, and a break of some sort was much more likely to produce in him the pressure that would eventually “go pop” than if they remained just sizzling here. “But we absolutely must go,” she said. “Philip will ask me about the play, and I couldn’t tell him that you and I simply sat talking till it was over.” “Why not?” said Peter. “Because it isn’t done. My dear, you and I have signed on to the conventionalities of life. Come along. A bore, but there it is. Besides, how would you account for your evening to Silvia? Dining at seven, you know. That requires a theatrical explanation.” “Oh, don’t be vulgar,” said Peter. “As if Silvia wouldn’t delight in my spending an evening with you.” “I know that,” said she. “Don’t lose your sense of humour, Peter. It was a mild kind of joke.” “Come on, then,” he said. “And as for its being my fault that we’re so late——”
  • 89. The second act was drawing to an end when they stole into their box. On the stage there was proceeding the most elementary of muddles, to which it was not in the least worth while to devote any ingenuity. It was clear at the first glance that these people who pretended to be servants were really landed gentry, and that just before the end the Earl (who had taken the house) would propose to the cook and be violently accepted. Psychologically they presented no point of interest. Far more engrossing to Nellie was the fact that she had got Peter with her, and the pleasure of that and the general problem it propounded was far more absorbing. Marriage had certainly quickened her emotional perceptions, and she inferred, from the extraordinary delight that it was to be with him again, how much in the interval she had missed him. She had no reason to complain, either, of the welcome he had given her, but it was manifest (how she could not definitely have said) that the quality of that was different from hers to him. To his sense, as he had openly stated, they had taken up the old attitude, the old intimacy, without break, but as she thought over that in the few minutes that elapsed before the act was finished, she found that, for her part, she did not altogether endorse his view. Certainly the old intimacy was there, firm and unshaken, but somehow, hovering over it, like a mist which to her eyes seemed to be luminous with tears, there was some new atmospheric condition, sunny and tremulous. Peter turned to her as the house sprang into light again. “Oh, what a waste of time,” he said. “We should have done much better to have left our elbows on the table. We’re always doing it too. Do you remember the last play at which we met? That time you were with Philip and I with Silvia and Mrs. Wardour. Then we had our talk afterwards; to- night we had it first. I like the other plan best.” Though Peter had here stated several things with which she was in cordial agreement, his tone was not in tune with the old footing, the old intimacy. Not many minutes ago it had been she who, in opposition to his inclination, had insisted on breaking their tête-à-tête; now, with all possible lightness of touch, she suggested its resumption. “I’ve seen enough,” she said. “I can tell Philip all about it. Let’s go back, my dear, and have half an hour’s more talk. It was my fault that we broke up; but how could I have told that the play would have been as silly as this?
  • 90. Welcome to our website – the perfect destination for book lovers and knowledge seekers. We believe that every book holds a new world, offering opportunities for learning, discovery, and personal growth. That’s why we are dedicated to bringing you a diverse collection of books, ranging from classic literature and specialized publications to self-development guides and children's books. More than just a book-buying platform, we strive to be a bridge connecting you with timeless cultural and intellectual values. With an elegant, user-friendly interface and a smart search system, you can quickly find the books that best suit your interests. Additionally, our special promotions and home delivery services help you save time and fully enjoy the joy of reading. Join us on a journey of knowledge exploration, passion nurturing, and personal growth every day! ebookbell.com