SlideShare a Scribd company logo
Visit https://ebookultra.com to download the full version and
explore more ebooks
Programming Microsoft SQL Server 2000 with
Microsoft Visual Basic NET 1st edition Edition
Rick Dobson
_____ Click the link below to download _____
https://ebookultra.com/download/programming-microsoft-
sql-server-2000-with-microsoft-visual-basic-net-1st-
edition-edition-rick-dobson/
Explore and download more ebooks at ebookultra.com
Here are some suggested products you might be interested in.
Click the link to download
Programming Microsoft Visual Basic NET Version 2003
Francesco Balena
https://ebookultra.com/download/programming-microsoft-visual-basic-
net-version-2003-francesco-balena/
Programming with Microsoft Visual Basic 2012 6th Edition
Diane Zak
https://ebookultra.com/download/programming-with-microsoft-visual-
basic-2012-6th-edition-diane-zak/
Microsoft SQL Server 2012 T SQL 1st Edition Tom Coffing
https://ebookultra.com/download/microsoft-sql-server-2012-t-sql-1st-
edition-tom-coffing/
Sams Teach Yourself Microsoft SQL Server 2000 in 21 Days
2nd Edition Richard Waymire
https://ebookultra.com/download/sams-teach-yourself-microsoft-sql-
server-2000-in-21-days-2nd-edition-richard-waymire/
Microsoft SQL Server 2008 Administration with Windows
PowerShell 1st Edition Ananthakumar Muthusamy
https://ebookultra.com/download/microsoft-sql-
server-2008-administration-with-windows-powershell-1st-edition-
ananthakumar-muthusamy/
Programming the Web with Visual Basic NET 1st Edition Lynn
Torkelson
https://ebookultra.com/download/programming-the-web-with-visual-basic-
net-1st-edition-lynn-torkelson/
Inside Microsoft SQL Server 2008 T SQL Querying 1st
Edition Itzik Ben-Gan
https://ebookultra.com/download/inside-microsoft-sql-
server-2008-t-sql-querying-1st-edition-itzik-ben-gan/
Mastering Microsoft Visual Basic 2008 Evangelos Petroutsos
https://ebookultra.com/download/mastering-microsoft-visual-
basic-2008-evangelos-petroutsos/
The Microsoft Data Warehouse Toolkit With SQL Server 2008
R2 and the Microsoft Business Intelligence Toolset 2nd
edition Edition Kimball
https://ebookultra.com/download/the-microsoft-data-warehouse-toolkit-
with-sql-server-2008-r2-and-the-microsoft-business-intelligence-
toolset-2nd-edition-edition-kimball/
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson
Programming Microsoft SQL Server 2000 with Microsoft
Visual Basic NET 1st edition Edition Rick Dobson Digital
Instant Download
Author(s): Rick Dobson, Paul Cornell
ISBN(s): 9780735615359, 0735615357
Edition: 1st edition
File Details: PDF, 10.60 MB
Year: 2002
Language: english
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick 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 Edition Rick 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
Another Random Scribd Document
with Unrelated Content
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson
The Project Gutenberg eBook of The Feather
This ebook is for the use of anyone anywhere in the United
States and most other parts of the world at no cost and with
almost no restrictions whatsoever. You may copy it, give it away
or re-use it under the terms of the Project Gutenberg License
included with this ebook or online at www.gutenberg.org. If you
are not located in the United States, you will have to check the
laws of the country where you are located before using this
eBook.
Title: The Feather
Author: Ford Madox Ford
Illustrator: Ford Madox Brown
Release date: December 10, 2015 [eBook #50658]
Most recently updated: October 22, 2024
Language: English
Credits: Produced by Emmy and the Online Distributed
Proofreading
Team at http://www.pgdp.net (This file was produced
from
images generously made available by The Internet
Archive)
*** START OF THE PROJECT GUTENBERG EBOOK THE FEATHER
***
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson
THE CHILDREN’S
LIBRARY
THE FEATHER
THE CHILDREN’S LIBRARY.
——————
THE BROWN OWL.
A CHINA CUP, and other Stories.
STORIES FROM FAIRYLAND.
TALES FROM THE MABINOGION.
THE STORY OF A PUPPET.
THE LITTLE PRINCESS.
IRISH FAIRY TALES.
AN ENCHANTED GARDEN.
LA BELLE NIVERNAISE.
THE FEATHER.
——————
(Others in the Press.)
“BUT THE EAGLE HAD THE BEST
OF IT AFTER ALL.”
THE FEATHER
BY
FORD H. MADOX HUEFFER
AUTHOR OF ‘THE BROWN OWL’
WITH FRONTISPIECE BY
F. MADOX BROWN
LONDON
T. FISHER UNWIN
1892
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson
TO JULIET
—————
‘True, I talk of dreams,
Which are the children of an idle brain,
Begot of nothing but vain fantasy,
Which is as thin of substance as the air.’
Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson
THE FEATHER
NCE upon a time there was a King who reigned over a
country as yet, for a reason you may learn later on,
undiscovered—a most lovely country, full of green dales
and groves of oak, a land of dappled meadows and
sweet rivers, a green cup in a circlet of mountains, in whose shadow
the grass was greenest; and the only road to enter the country lay
up steep, boiling waterfalls, and thereafter through rugged passes,
the channels that the rivers had cut for themselves. Therefore, as
you may imagine, the dwellers in the land were little troubled by
inroads of hostile nations; and they lived peaceful lives, managing
their own affairs, and troubling little about the rest of the world.
Now this King, like many kings before and after him, had a
daughter who, while very young, had, I am sorry to say, been very
self-willed; and the King, on the death of his wife, finding himself
utterly unable to manage the Princess, handed her over to the care
of an aged nurse, who, however, was not much more successful—
but that is neither here nor there.
For years everything went on smoothly, and it seemed as if
everything intended to go on smoothly until doomsday, in which
case this history would probably never have been written. But one
evening in summer the Princess and her nurse, who had by this time
become less able than ever to manage her charge, sat on a terrace
facing the west. The Princess had been amusing herself by pelting
the swans swimming in the river with rose-leaves, which the
indignant swans snapped up as they fluttered down on the air or
floated by on the river.
But after a time she began to tire of this pastime, and sitting
down, looked at the sun that was just setting, a blinding glare of
orange flame behind the black hills. Suddenly she turned to the
nurse and said:
‘What’s on the other side of the hills?’
‘Lawk-a-mussy-me, miss!’ answered the nurse, ‘I’m sure I don’t
know. What a question to ask!’
‘Then why don’t you ask some one who has been there?’
‘Because no one ever has, miss.’
‘But why not?’
‘Because there’s a fiery serpent that eats every one who comes
near the hills; and if you’re not eaten up, you’re bound to tumble
down a precipice that’s nearly three miles deep, before you can get
over the hills.’
‘Oh, what fun! Let’s go,’ said the Princess, by no means awed. But
the nurse shook her head.
‘No, miss, I won’t go; and I’m sure your pa won’t let you go.’
‘Oh yes, he will; let’s go and ask him.’
But at that moment a black shadow came across the sun, and the
swans, with a terrified ‘honk, honk,’ darted across the water to hide
themselves in the reeds on the other side of the river, churning dark
tracks in the purple of the sunlit water’s glassy calmness.
‘Oh dear! oh dear! it’s a boggles, and it’s coming this way,’ cried
the nurse.
‘But what is a boggles, nurse?’
‘Oh dear, it’s coming! Come into the house and I’ll tell you—
come.’
‘Not until you tell me what a boggles is.’
The nurse perforce gave in.
‘A boggles is a thing with a hooked beak and a squeaky voice,
with hair like snakes in corkscrews; and it haunts houses and carries
off things; and when it once gets in it never leaves again—oh dear,
it’s on us! Oh-h-h!’
Her cries only made the thing see them sooner. It was only an
eagle, not a boggles; but it was on the look-out for food, and the
sun shining on the Princess’s hair had caught its eyes, and in spite of
the cries of the nurse it swooped down, and, seizing the Princess in
its claws, began to carry her off. The nurse, however, held on to her
valiantly, screaming all the while for help; but the eagle had the best
of it after all, for it carried up, not only the Princess, but the nurse
also.
The nurse held on to her charge for some seconds, but finding
the attempt useless she let go her hold; and since it happened that
at the moment they were over the river, she fell into it with a great
splash, and was drifted on shore by the current.
Thus the Princess was carried off; and although the land far and
wide was searched, no traces of her were discoverable. You may
imagine for yourself what sorrow and rage the King indulged in. He
turned the nurse off without warning, and even, in a paroxysm of
rage, kicked one of his pages downstairs; nevertheless that did not
bring back the Princess.
As a last resource he consulted a wise woman (ill-natured people
called her a witch) who lived near the palace. But the witch could
only say that the Princess would return some day, but she couldn’t
or wouldn’t say when, even though the King threatened to burn her.
So it was all of no use, and the King was, and remained, in despair.
But, since his Majesty is not the important personage in the story,
we may as well leave him and return to the Princess.
She, as you can think, was not particularly happy or comfortable,
for the claws of the eagle pinched her, and besides, she was very
frightened; for, you see, she didn’t know that it wasn’t a boggles, as
the nurse had called it, and a boggles is a great deal worse than the
worst eagle ever invented.
Meanwhile the eagle continued flying straight towards the sun,
which was getting lower and lower, so that by the time they reached
the mountains it was dark altogether. But the eagle didn’t seem at all
afraid of the darkness, and just went on flying as if nothing had
happened, until suddenly it let the Princess down on a rock—at least,
that was what it seemed to her to be. Not knowing what else to do,
she sat where the eagle had let her fall, for she remembered
something about the precipice three miles deep, and she did not at
all wish to tumble down that.
She expected that the eagle would set to and make a meal off
her at once. But somehow or other, either it had had enough to eat
during the day, or else did not like to begin to have supper so late
for fear of nightmare; at any rate, it abstained, and that was the
most interesting matter to her. Everything was so quiet around that
at last, in spite of herself, she fell asleep. She slept quite easily until
daylight, although the hardness of the rock was certainly somewhat
unpleasant. When she opened her eyes it was already light, and the
sun at her back was darting black shadows of the jagged mountains
on to the shimmering gray sea of mist that veiled the land below.
Her first thought was naturally of the eagle, and she did not need to
look very far for him, since he was washing himself in a little pool
close by, keeping an eye on her the while.
As soon as he saw her move he gave himself a final shake, so
that the water flew all around, sparkling in the sunlight; after which
he came towards her by hops until he was quite close—rather too
close, she thought. Nevertheless she did not move, having heard
somewhere that, under the circumstances, that is the worst thing to
do; she also remembered animals cannot stand being looked at
steadily by the human eye, therefore she looked very steadfastly at
the eyes of the eagle. But the remedy did not seem to work well in
this case, for the glassy yellow eyes of the bird looked bad-
tempered, and it winked angrily, seeming to say, ‘Whom are you
staring at?’ And then it began to stretch out its bill towards her until
it was within a few inches of her face. This was more than she could
stand, and she said sharply, ‘Take your head away.’
The eagle, however, took no notice whatever of this; and seeing
nothing better to do, she lifted up her hand and gave it a smart box
on the ear, or rather on the place where its ear should have been.
The eagle drew back its beak in a hurry and scratched its head with
one claw as if it were puzzled. After a moment’s reflection it put out
its head again, and once more the Princess lifted up her hand; but
when the eagle saw that it jumped backwards in a hurry, as if it did
not care to receive a second box on the ear, and began to stride
sulkily away as if it thought it better to wait a while. When it reached
the edge of the rock—for I have forgotten to tell you that they were
on a flat rock at the top of a mountain—it sat preening its feathers in
a sulky manner, as if it imagined itself a very ill-used bird; moreover,
although it seemed inclined to remain there a long time, I need not
tell you that the Princess had no objections. However, after a time
even the waiting began to grow unpleasant; but suddenly a peculiar
sound, as of something shooting through the air, came from below,
and the eagle gave a leap and fell down a mass of tumbled feathers
with an arrow quivering in their centre, and, with hardly a shudder, it
was dead.
The Princess, as you may imagine, was a good deal startled by
this sudden occurrence, but I cannot say she was very sorry for the
eagle; on the contrary, she was rather glad to be rid of him, and it
suddenly came into her head that the man who had shot the arrow
might possibly be somewhere below, and in that case might come
up and save her if she called to him. So she tried to get up, but she
was so stiff that she could hardly move, and when she did stand up
she had pins and needles in one of her feet, and had to stamp hard
on the ground before it would go away. So that it was some time
before she got to the edge and looked over. Now it happened that,
just as she bent carefully forward to look down the side, the head of
a man appeared over the edge, and his hands were so near her that
he almost caught hold of her foot as he put them up to help himself.
As she drew back a little to let him have room, he suddenly noticed
her, and almost let go his hold in astonishment.
‘Hullo, little girl,’ he said; ‘how did you come here? It’s rather early
in the morning for you to be up. But who are you when you’re at
home?’
‘I’m the daughter of King Caret.’
‘King how much?’
‘King Caret, I said; and I should be glad if you would help me
down from this height, and show me the way back.’
‘How on earth can I show you the way back when I don’t know
who King Caret is?’
‘But surely you must know who he is?’
‘Never heard of him. What’s he like, and what’s he king of?’
‘He’s the King of Aoland.’
‘And where’s Aoland?’
‘I don’t know—it’s somewhere over those mountains—the eagle
brought me here, you know.’
‘Ah! the eagle brought you here, did he? It’s a little habit he’s got;
he’s carried off no end of my kids and young sheep, so I suppose he
thought he’d try a change and carry off one of King Turnip—I mean
Caret’s. But if he brought you from over the mountains you won’t
get back in a hurry, I can tell you; you’d have to jump up a precipice
three miles high, and then you’d be eaten by old Kinchof the
dragon.’
‘Oh dear! then I shall never get back!’
‘No, I’m afraid you won’t. But don’t begin to cry now—there,
there—and I’ll take you to King Mumkie; he’s the king of this
country, you know.’
‘What an awful name—Mumkie!’
‘Yes, it is rather unpleasant, isn’t it? And then, he’s a usurper—he
drove the last king out and made himself king instead. He used to be
a cat’s-meat man, but he got up an army and drove the other off the
throne, and now he’s turned into a gardener—his name’s
Abbonamento.’
‘Oh, never mind what his name is, only get me down—I’m awfully
hungry; for you see I’ve been up here all night.’
‘Oh! all right. But I say, how are you going to get down—you can’t
climb, can you?’
‘I don’t know,’ she answered; ‘I’ve never tried.’
‘Then you can be sure you can’t. The only thing seems to be for
me to carry you down.’
But the Princess did not seem to relish the idea at all.
‘You might let me drop, you know; it’s rather steep.’ And it was
pretty steep, too—about as steep as the wall of a house, and a good
deal higher than a very high house. However, it seemed to be the
only thing to do, so she let herself be carried down. The man took
her on one arm, and yet seemed to climb down about as easily as if
he were going downstairs. However, the Princess did not notice that,
since she kept her eyes shut hard, for, to tell the truth, she was
rather nervous.
But at last they were at the bottom, and he let her down on to
the ground.
‘Now, what are you going to do?’ he said.
‘I don’t know at all. What can I do?’
‘You’d better go and see King Mumkie and ask him what to do.’
‘But he has got such a dreadful name; it sounds as if he was
awfully ugly,’ she said.
‘But he’s not at all; he’s just like me, and I’m sure I’m handsome
enough for any one.’
The Princess looked at him now for the first time; for you see, she
had not noticed him very much while she was on the mountain. But
now she could hardly repress a shudder; for he was awfully ugly. To
begin with, he was big enough for any giant, and then his hair was
of a purple hue, and his eyes of a delicate sea-green that flashed in
the shade like a cat’s; and then his nose was awfully red, and
shaped like a mangel-wurzel; and his teeth, which were long and
bright green, shone in the sun like danger-signals. Altogether he was
not prepossessing; and the Princess could hardly help smiling when
he said that the King was as handsome as himself. However, he went
on:
‘My name’s Wopole; I’m King Mumkie’s falconer, and so I can tell
you all about him. Come, let’s go towards the town.’
And as there seemed nothing else to do, she set out with him;
but he walked so fast that she could hardly keep up.
‘How slowly you do walk!’ he grumbled in a bad-tempered
manner; ‘can’t you keep up? Come along, I can’t wait all day.’ And
he went on faster than ever, so that she had to run to keep up with
him. Suddenly he stopped as if he had been shot.
‘Confound it, I’ve forgotten to bring the eagle, and I shall have to
go all the way back and get it. Oh—ouch!’ And he began to howl in
such a dreadful manner that the Princess felt quite relieved when he
turned and ran towards the hill at the top of his speed, howling all
the way.
‘What on earth shall I do now?’ thought the Princess. ‘If I wait for
this dreadful giant, goodness knows what may happen, and then his
king has such an unpleasant name; at any rate, I should like some
breakfast, for I’m awfully hungry. I think I’ll go on towards the town,
and see if I can’t find some one who’ll show me the way home.’
So she went on down the lane for some way, until, coming to a
place where a stream went across the path, she knelt down and
scooped up a little water in the palm of her hand and drank it; for,
you see, the sun was very hot now, and the heat made her throat
feel quite dry and parched. When she had finished she went and lay
down in the long grass that bordered the road, for she was rather
tired. She intended to wait till some one came along, only she was
quite resolved not to go with the giant at any rate. So she lay quietly
in the shade listening to the loud humming of the bees and the chirp
of a linnet that was pluming itself, swinging on a bough above her
head.
She had not been waiting long before she heard a dreadful noise
behind her coming down the road, and in a few minutes she
recognised the voice of the giant, who seemed to be in a terrible
temper. Gradually the sound of his voice and his footsteps came
nearer. The Princess did not know what to do, for if she tried to run
away he would only catch her up; so she lay perfectly still, hoping he
would pass her without seeing her. And that is just what did happen;
for, in a few moments, he came rushing round the corner shouting
out, ‘Stop! stop! will you?’ And as his eyes were fixed on the road far
in advance, of course he did not notice her, and was soon round
another bend in the road. The Princess noticed that he had the eagle
hanging with its claws round his neck, and the jolting, as he went
by, had shaken one of its large tail feathers out, and as soon as she
had got over her fright, she went and picked it up out of the dusty
road.
Just as she picked it up, the clatter of feet running along the road
came to her ears, and for a moment she feared that the giant had
returned; but soon a cow trotted round the bend and stopped at the
stream to drink, presently another, and then a third. Each of them
took a long look at the Princess, and then bent down its head to
take a draught out of the stream. Just then an old man came round
the corner, and when he saw the cows had stopped he called out:
‘Gee on, Lightfoot; now, Daisy; come up, Cherry,’ and the cows
gave their heads a toss, and walked slowly through the stream.
The Princess hurried to one side of the road, for, like many
people, she had an instinctive dread of anything like a cow or a bull.
The old man noticed it and smiled.
‘Oh, you needn’t be afraid, miss, they won’t hurt you,’ he said;
but all the same, she didn’t care to go too near them. ‘They’ve just
been frightened by Wopole, King Mumkie’s falconer,’ he went on.
‘Wopole came running round the corner suddenly, and almost
knocked Lightfoot—that’s the dun cow—over. He was roaring out
“Where is she?” awfully loud. I pity her when he gets her, whoever
she is.’
‘But who is she?’ asked the Princess.
‘I don’t know—how should I?’
‘Oh, I only thought you might know. But what will he do with her
when he gets her?’
‘I don’t know; fry her in lard or something—that’s what they
generally do to strangers in the town now.’
‘Oh dear!’ said the Princess; ‘how am I to get away from him?’
The old man looked at her curiously.
‘Oh! you’re her,’ he said.
‘I rather think I am. But how am I to get away?’ she answered.
‘If you’ll come with me I’ll take you to my cottage over there, and
they’ll never think of looking for you there.’
But the Princess did not exactly like the idea.
‘Aren’t you one of these people?’ she asked; ‘because I don’t
relish being fried in lard, or oil, or anything else.’
But the old man shook his head.
‘Good gracious me, no!’ he said. ‘I wouldn’t let them roast the last
stranger that came to the town, and so they turned me out.’
‘Oh,’ said the Princess, ‘then you must be King Abominable.’
‘I am Abbonamento.’
‘Then I suppose I shall be safe with you?’
‘Quite safe, if you like to come; only just help me to drive the
cows.’ And the old man called to his animals who were browsing in
the grass at the wayside, and they trudged quietly on till they came
to a gate in the hedge. This they waited for the old man to open for
them, and then went through the meadow until they came to a little
farmhouse half hidden by trees.
‘This is my house,’ the King said. ‘Just wait a moment till I have
put the cows in the byre, and then I’ll come back and let you in; for
you see my wife’s away at the market, and there’s no one else at
home.’
So the Princess stopped where she was, and the old man went
whistling round to the back of the house driving his cows before
him.
It was a very small house, with the thatched roof coming so low
down that you could touch it almost with your hand, and the
windows were quite overshadowed by it. Over a little arbour of
trellis-work before the door ran a rose-tree of deep red flowers, and
the roses were full of bees that came from the hives arranged on
benches under the eaves, and a few chickens were asleep on one
leg under the porch.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
Let us accompany you on the journey of exploring knowledge and
personal growth!
ebookultra.com

More Related Content

Similar to Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson (20)

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
 
Vb and asp.net
Vb and asp.netVb and asp.net
Vb and asp.net
sanjay joshi
 
ASPNET for PHP Developers
ASPNET for PHP DevelopersASPNET for PHP Developers
ASPNET for PHP Developers
Wes Yanaga
 
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
 
Foundry Management System Desktop Application
Foundry Management System Desktop Application Foundry Management System Desktop Application
Foundry Management System Desktop Application
Dharmendra Sid
 
.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
 
Vb & asp .net
Vb & asp .netVb & asp .net
Vb & asp .net
Lakhmichand institute of technology
 
.NET presentation
.NET presentation.NET presentation
.NET presentation
Himanshu Bhalla
 
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
 
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
 
Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...
Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...
Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...
khlifrushit84
 
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.
 
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
 
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
 
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
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
Syed Zaid Irshad
 
Vb.net class notes
Vb.net class notesVb.net class notes
Vb.net class notes
priyadharshini murugan
 
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
 
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
 
ASPNET for PHP Developers
ASPNET for PHP DevelopersASPNET for PHP Developers
ASPNET for PHP Developers
Wes Yanaga
 
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
 
Foundry Management System Desktop Application
Foundry Management System Desktop Application Foundry Management System Desktop Application
Foundry Management System Desktop Application
Dharmendra Sid
 
.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
 
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
 
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
 
Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...
Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...
Mcts Selfpaced Training Kit Exam 70516 Accessing Data With Microsoft Net Fram...
khlifrushit84
 
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
 
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
 
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
 
DBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_SolutionDBMS_Lab_Manual_&_Solution
DBMS_Lab_Manual_&_Solution
Syed Zaid Irshad
 
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)

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.
 
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
BUSINESS QUIZ PRELIMS | QUIZ CLUB OF PSGCAS | 9 SEPTEMBER 2024
Quiz Club of PSG College of Arts & Science
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
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
 
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
 
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
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
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
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
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)
 
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
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive LearningSustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
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
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti MpdBasic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Basic English for Communication - Dr Hj Euis Eti Rohaeti Mpd
Restu Bias Primandhika
 
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 4 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
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
 
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
 
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
 
How to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 EmployeeHow to Manage & Create a New Department in Odoo 18 Employee
How to Manage & Create a New Department in Odoo 18 Employee
Celine George
 
How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18How to Manage Upselling of Subscriptions in Odoo 18
How to Manage Upselling of Subscriptions in Odoo 18
Celine George
 
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_HyderabadWebcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Webcrawler_Mule_AIChain_MuleSoft_Meetup_Hyderabad
Veera Pallapu
 
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
 
How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18How to Configure Vendor Management in Lunch App of Odoo 18
How to Configure Vendor Management in Lunch App of Odoo 18
Celine George
 
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
 
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKANMATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
MATERI PPT TOPIK 1 LANDASAN FILOSOFIS PENDIDIKAN
aditya23173
 
Sustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive LearningSustainable Innovation with Immersive Learning
Sustainable Innovation with Immersive Learning
Leonel Morgado
 
Revista digital preescolar en transformación
Revista digital preescolar en transformaciónRevista digital preescolar en transformación
Revista digital preescolar en transformación
guerragallardo26
 
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
 
Black and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdfBlack and White Illustrative Group Project Presentation.pdf (1).pdf
Black and White Illustrative Group Project Presentation.pdf (1).pdf
AnnasofiaUrsini
 
Ad

Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson

  • 1. Visit https://ebookultra.com to download the full version and explore more ebooks Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson _____ Click the link below to download _____ https://ebookultra.com/download/programming-microsoft- sql-server-2000-with-microsoft-visual-basic-net-1st- edition-edition-rick-dobson/ Explore and download more ebooks at ebookultra.com
  • 2. Here are some suggested products you might be interested in. Click the link to download Programming Microsoft Visual Basic NET Version 2003 Francesco Balena https://ebookultra.com/download/programming-microsoft-visual-basic- net-version-2003-francesco-balena/ Programming with Microsoft Visual Basic 2012 6th Edition Diane Zak https://ebookultra.com/download/programming-with-microsoft-visual- basic-2012-6th-edition-diane-zak/ Microsoft SQL Server 2012 T SQL 1st Edition Tom Coffing https://ebookultra.com/download/microsoft-sql-server-2012-t-sql-1st- edition-tom-coffing/ Sams Teach Yourself Microsoft SQL Server 2000 in 21 Days 2nd Edition Richard Waymire https://ebookultra.com/download/sams-teach-yourself-microsoft-sql- server-2000-in-21-days-2nd-edition-richard-waymire/
  • 3. Microsoft SQL Server 2008 Administration with Windows PowerShell 1st Edition Ananthakumar Muthusamy https://ebookultra.com/download/microsoft-sql- server-2008-administration-with-windows-powershell-1st-edition- ananthakumar-muthusamy/ Programming the Web with Visual Basic NET 1st Edition Lynn Torkelson https://ebookultra.com/download/programming-the-web-with-visual-basic- net-1st-edition-lynn-torkelson/ Inside Microsoft SQL Server 2008 T SQL Querying 1st Edition Itzik Ben-Gan https://ebookultra.com/download/inside-microsoft-sql- server-2008-t-sql-querying-1st-edition-itzik-ben-gan/ Mastering Microsoft Visual Basic 2008 Evangelos Petroutsos https://ebookultra.com/download/mastering-microsoft-visual- basic-2008-evangelos-petroutsos/ The Microsoft Data Warehouse Toolkit With SQL Server 2008 R2 and the Microsoft Business Intelligence Toolset 2nd edition Edition Kimball https://ebookultra.com/download/the-microsoft-data-warehouse-toolkit- with-sql-server-2008-r2-and-the-microsoft-business-intelligence- toolset-2nd-edition-edition-kimball/
  • 5. Programming Microsoft SQL Server 2000 with Microsoft Visual Basic NET 1st edition Edition Rick Dobson Digital Instant Download Author(s): Rick Dobson, Paul Cornell ISBN(s): 9780735615359, 0735615357 Edition: 1st edition File Details: PDF, 10.60 MB Year: 2002 Language: english
  • 7. 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
  • 8. 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
  • 9. 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
  • 10. 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
  • 11. 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.
  • 12. 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
  • 13. 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
  • 14. (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
  • 15. 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
  • 16. 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
  • 17. 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
  • 18. 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.
  • 19. 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.
  • 20. 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.
  • 21. 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
  • 22. 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
  • 23. 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.
  • 24. 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
  • 25. 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.
  • 26. 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,
  • 27. 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.
  • 28. 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
  • 29. 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.
  • 30. 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.
  • 31. 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
  • 32. 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.
  • 33. 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
  • 34. ’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
  • 35. 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.
  • 36. 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.
  • 37. 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
  • 38. 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.
  • 39. 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) .
  • 41. 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
  • 42. 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
  • 43. 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
  • 44. 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.
  • 45. 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
  • 46. 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
  • 47. 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
  • 48. 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
  • 49. 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.
  • 50. 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
  • 51. Another Random Scribd Document with Unrelated Content
  • 55. The Project Gutenberg eBook of The Feather
  • 56. This ebook is for the use of anyone anywhere in the United States and most other parts of the world at no cost and with almost no restrictions whatsoever. You may copy it, give it away or re-use it under the terms of the Project Gutenberg License included with this ebook or online at www.gutenberg.org. If you are not located in the United States, you will have to check the laws of the country where you are located before using this eBook. Title: The Feather Author: Ford Madox Ford Illustrator: Ford Madox Brown Release date: December 10, 2015 [eBook #50658] Most recently updated: October 22, 2024 Language: English Credits: Produced by Emmy and the Online Distributed Proofreading Team at http://www.pgdp.net (This file was produced from images generously made available by The Internet Archive) *** START OF THE PROJECT GUTENBERG EBOOK THE FEATHER ***
  • 59. THE CHILDREN’S LIBRARY. —————— THE BROWN OWL. A CHINA CUP, and other Stories. STORIES FROM FAIRYLAND. TALES FROM THE MABINOGION. THE STORY OF A PUPPET. THE LITTLE PRINCESS. IRISH FAIRY TALES. AN ENCHANTED GARDEN. LA BELLE NIVERNAISE. THE FEATHER. —————— (Others in the Press.)
  • 60. “BUT THE EAGLE HAD THE BEST OF IT AFTER ALL.”
  • 61. THE FEATHER BY FORD H. MADOX HUEFFER AUTHOR OF ‘THE BROWN OWL’ WITH FRONTISPIECE BY F. MADOX BROWN LONDON T. FISHER UNWIN 1892
  • 63. TO JULIET ————— ‘True, I talk of dreams, Which are the children of an idle brain, Begot of nothing but vain fantasy, Which is as thin of substance as the air.’
  • 65. THE FEATHER NCE upon a time there was a King who reigned over a country as yet, for a reason you may learn later on, undiscovered—a most lovely country, full of green dales and groves of oak, a land of dappled meadows and sweet rivers, a green cup in a circlet of mountains, in whose shadow the grass was greenest; and the only road to enter the country lay up steep, boiling waterfalls, and thereafter through rugged passes, the channels that the rivers had cut for themselves. Therefore, as you may imagine, the dwellers in the land were little troubled by inroads of hostile nations; and they lived peaceful lives, managing their own affairs, and troubling little about the rest of the world. Now this King, like many kings before and after him, had a daughter who, while very young, had, I am sorry to say, been very self-willed; and the King, on the death of his wife, finding himself utterly unable to manage the Princess, handed her over to the care of an aged nurse, who, however, was not much more successful— but that is neither here nor there. For years everything went on smoothly, and it seemed as if everything intended to go on smoothly until doomsday, in which case this history would probably never have been written. But one evening in summer the Princess and her nurse, who had by this time become less able than ever to manage her charge, sat on a terrace facing the west. The Princess had been amusing herself by pelting the swans swimming in the river with rose-leaves, which the indignant swans snapped up as they fluttered down on the air or floated by on the river. But after a time she began to tire of this pastime, and sitting down, looked at the sun that was just setting, a blinding glare of
  • 66. orange flame behind the black hills. Suddenly she turned to the nurse and said: ‘What’s on the other side of the hills?’ ‘Lawk-a-mussy-me, miss!’ answered the nurse, ‘I’m sure I don’t know. What a question to ask!’ ‘Then why don’t you ask some one who has been there?’ ‘Because no one ever has, miss.’ ‘But why not?’ ‘Because there’s a fiery serpent that eats every one who comes near the hills; and if you’re not eaten up, you’re bound to tumble down a precipice that’s nearly three miles deep, before you can get over the hills.’ ‘Oh, what fun! Let’s go,’ said the Princess, by no means awed. But the nurse shook her head. ‘No, miss, I won’t go; and I’m sure your pa won’t let you go.’ ‘Oh yes, he will; let’s go and ask him.’ But at that moment a black shadow came across the sun, and the swans, with a terrified ‘honk, honk,’ darted across the water to hide themselves in the reeds on the other side of the river, churning dark tracks in the purple of the sunlit water’s glassy calmness. ‘Oh dear! oh dear! it’s a boggles, and it’s coming this way,’ cried the nurse. ‘But what is a boggles, nurse?’ ‘Oh dear, it’s coming! Come into the house and I’ll tell you— come.’ ‘Not until you tell me what a boggles is.’
  • 67. The nurse perforce gave in. ‘A boggles is a thing with a hooked beak and a squeaky voice, with hair like snakes in corkscrews; and it haunts houses and carries off things; and when it once gets in it never leaves again—oh dear, it’s on us! Oh-h-h!’ Her cries only made the thing see them sooner. It was only an eagle, not a boggles; but it was on the look-out for food, and the sun shining on the Princess’s hair had caught its eyes, and in spite of the cries of the nurse it swooped down, and, seizing the Princess in its claws, began to carry her off. The nurse, however, held on to her valiantly, screaming all the while for help; but the eagle had the best of it after all, for it carried up, not only the Princess, but the nurse also. The nurse held on to her charge for some seconds, but finding the attempt useless she let go her hold; and since it happened that at the moment they were over the river, she fell into it with a great splash, and was drifted on shore by the current. Thus the Princess was carried off; and although the land far and wide was searched, no traces of her were discoverable. You may imagine for yourself what sorrow and rage the King indulged in. He turned the nurse off without warning, and even, in a paroxysm of rage, kicked one of his pages downstairs; nevertheless that did not bring back the Princess. As a last resource he consulted a wise woman (ill-natured people called her a witch) who lived near the palace. But the witch could only say that the Princess would return some day, but she couldn’t or wouldn’t say when, even though the King threatened to burn her. So it was all of no use, and the King was, and remained, in despair. But, since his Majesty is not the important personage in the story, we may as well leave him and return to the Princess. She, as you can think, was not particularly happy or comfortable, for the claws of the eagle pinched her, and besides, she was very
  • 68. frightened; for, you see, she didn’t know that it wasn’t a boggles, as the nurse had called it, and a boggles is a great deal worse than the worst eagle ever invented. Meanwhile the eagle continued flying straight towards the sun, which was getting lower and lower, so that by the time they reached the mountains it was dark altogether. But the eagle didn’t seem at all afraid of the darkness, and just went on flying as if nothing had happened, until suddenly it let the Princess down on a rock—at least, that was what it seemed to her to be. Not knowing what else to do, she sat where the eagle had let her fall, for she remembered something about the precipice three miles deep, and she did not at all wish to tumble down that. She expected that the eagle would set to and make a meal off her at once. But somehow or other, either it had had enough to eat during the day, or else did not like to begin to have supper so late for fear of nightmare; at any rate, it abstained, and that was the most interesting matter to her. Everything was so quiet around that at last, in spite of herself, she fell asleep. She slept quite easily until daylight, although the hardness of the rock was certainly somewhat unpleasant. When she opened her eyes it was already light, and the sun at her back was darting black shadows of the jagged mountains on to the shimmering gray sea of mist that veiled the land below. Her first thought was naturally of the eagle, and she did not need to look very far for him, since he was washing himself in a little pool close by, keeping an eye on her the while. As soon as he saw her move he gave himself a final shake, so that the water flew all around, sparkling in the sunlight; after which he came towards her by hops until he was quite close—rather too close, she thought. Nevertheless she did not move, having heard somewhere that, under the circumstances, that is the worst thing to do; she also remembered animals cannot stand being looked at steadily by the human eye, therefore she looked very steadfastly at the eyes of the eagle. But the remedy did not seem to work well in this case, for the glassy yellow eyes of the bird looked bad-
  • 69. tempered, and it winked angrily, seeming to say, ‘Whom are you staring at?’ And then it began to stretch out its bill towards her until it was within a few inches of her face. This was more than she could stand, and she said sharply, ‘Take your head away.’ The eagle, however, took no notice whatever of this; and seeing nothing better to do, she lifted up her hand and gave it a smart box on the ear, or rather on the place where its ear should have been. The eagle drew back its beak in a hurry and scratched its head with one claw as if it were puzzled. After a moment’s reflection it put out its head again, and once more the Princess lifted up her hand; but when the eagle saw that it jumped backwards in a hurry, as if it did not care to receive a second box on the ear, and began to stride sulkily away as if it thought it better to wait a while. When it reached the edge of the rock—for I have forgotten to tell you that they were on a flat rock at the top of a mountain—it sat preening its feathers in a sulky manner, as if it imagined itself a very ill-used bird; moreover, although it seemed inclined to remain there a long time, I need not tell you that the Princess had no objections. However, after a time even the waiting began to grow unpleasant; but suddenly a peculiar sound, as of something shooting through the air, came from below, and the eagle gave a leap and fell down a mass of tumbled feathers with an arrow quivering in their centre, and, with hardly a shudder, it was dead. The Princess, as you may imagine, was a good deal startled by this sudden occurrence, but I cannot say she was very sorry for the eagle; on the contrary, she was rather glad to be rid of him, and it suddenly came into her head that the man who had shot the arrow might possibly be somewhere below, and in that case might come up and save her if she called to him. So she tried to get up, but she was so stiff that she could hardly move, and when she did stand up she had pins and needles in one of her feet, and had to stamp hard on the ground before it would go away. So that it was some time before she got to the edge and looked over. Now it happened that, just as she bent carefully forward to look down the side, the head of
  • 70. a man appeared over the edge, and his hands were so near her that he almost caught hold of her foot as he put them up to help himself. As she drew back a little to let him have room, he suddenly noticed her, and almost let go his hold in astonishment. ‘Hullo, little girl,’ he said; ‘how did you come here? It’s rather early in the morning for you to be up. But who are you when you’re at home?’ ‘I’m the daughter of King Caret.’ ‘King how much?’ ‘King Caret, I said; and I should be glad if you would help me down from this height, and show me the way back.’ ‘How on earth can I show you the way back when I don’t know who King Caret is?’ ‘But surely you must know who he is?’ ‘Never heard of him. What’s he like, and what’s he king of?’ ‘He’s the King of Aoland.’ ‘And where’s Aoland?’ ‘I don’t know—it’s somewhere over those mountains—the eagle brought me here, you know.’ ‘Ah! the eagle brought you here, did he? It’s a little habit he’s got; he’s carried off no end of my kids and young sheep, so I suppose he thought he’d try a change and carry off one of King Turnip—I mean Caret’s. But if he brought you from over the mountains you won’t get back in a hurry, I can tell you; you’d have to jump up a precipice three miles high, and then you’d be eaten by old Kinchof the dragon.’ ‘Oh dear! then I shall never get back!’
  • 71. ‘No, I’m afraid you won’t. But don’t begin to cry now—there, there—and I’ll take you to King Mumkie; he’s the king of this country, you know.’ ‘What an awful name—Mumkie!’ ‘Yes, it is rather unpleasant, isn’t it? And then, he’s a usurper—he drove the last king out and made himself king instead. He used to be a cat’s-meat man, but he got up an army and drove the other off the throne, and now he’s turned into a gardener—his name’s Abbonamento.’ ‘Oh, never mind what his name is, only get me down—I’m awfully hungry; for you see I’ve been up here all night.’ ‘Oh! all right. But I say, how are you going to get down—you can’t climb, can you?’ ‘I don’t know,’ she answered; ‘I’ve never tried.’ ‘Then you can be sure you can’t. The only thing seems to be for me to carry you down.’ But the Princess did not seem to relish the idea at all. ‘You might let me drop, you know; it’s rather steep.’ And it was pretty steep, too—about as steep as the wall of a house, and a good deal higher than a very high house. However, it seemed to be the only thing to do, so she let herself be carried down. The man took her on one arm, and yet seemed to climb down about as easily as if he were going downstairs. However, the Princess did not notice that, since she kept her eyes shut hard, for, to tell the truth, she was rather nervous. But at last they were at the bottom, and he let her down on to the ground. ‘Now, what are you going to do?’ he said. ‘I don’t know at all. What can I do?’
  • 72. ‘You’d better go and see King Mumkie and ask him what to do.’ ‘But he has got such a dreadful name; it sounds as if he was awfully ugly,’ she said. ‘But he’s not at all; he’s just like me, and I’m sure I’m handsome enough for any one.’ The Princess looked at him now for the first time; for you see, she had not noticed him very much while she was on the mountain. But now she could hardly repress a shudder; for he was awfully ugly. To begin with, he was big enough for any giant, and then his hair was of a purple hue, and his eyes of a delicate sea-green that flashed in the shade like a cat’s; and then his nose was awfully red, and shaped like a mangel-wurzel; and his teeth, which were long and bright green, shone in the sun like danger-signals. Altogether he was not prepossessing; and the Princess could hardly help smiling when he said that the King was as handsome as himself. However, he went on: ‘My name’s Wopole; I’m King Mumkie’s falconer, and so I can tell you all about him. Come, let’s go towards the town.’ And as there seemed nothing else to do, she set out with him; but he walked so fast that she could hardly keep up. ‘How slowly you do walk!’ he grumbled in a bad-tempered manner; ‘can’t you keep up? Come along, I can’t wait all day.’ And he went on faster than ever, so that she had to run to keep up with him. Suddenly he stopped as if he had been shot. ‘Confound it, I’ve forgotten to bring the eagle, and I shall have to go all the way back and get it. Oh—ouch!’ And he began to howl in such a dreadful manner that the Princess felt quite relieved when he turned and ran towards the hill at the top of his speed, howling all the way. ‘What on earth shall I do now?’ thought the Princess. ‘If I wait for this dreadful giant, goodness knows what may happen, and then his
  • 73. king has such an unpleasant name; at any rate, I should like some breakfast, for I’m awfully hungry. I think I’ll go on towards the town, and see if I can’t find some one who’ll show me the way home.’ So she went on down the lane for some way, until, coming to a place where a stream went across the path, she knelt down and scooped up a little water in the palm of her hand and drank it; for, you see, the sun was very hot now, and the heat made her throat feel quite dry and parched. When she had finished she went and lay down in the long grass that bordered the road, for she was rather tired. She intended to wait till some one came along, only she was quite resolved not to go with the giant at any rate. So she lay quietly in the shade listening to the loud humming of the bees and the chirp of a linnet that was pluming itself, swinging on a bough above her head. She had not been waiting long before she heard a dreadful noise behind her coming down the road, and in a few minutes she recognised the voice of the giant, who seemed to be in a terrible temper. Gradually the sound of his voice and his footsteps came nearer. The Princess did not know what to do, for if she tried to run away he would only catch her up; so she lay perfectly still, hoping he would pass her without seeing her. And that is just what did happen; for, in a few moments, he came rushing round the corner shouting out, ‘Stop! stop! will you?’ And as his eyes were fixed on the road far in advance, of course he did not notice her, and was soon round another bend in the road. The Princess noticed that he had the eagle hanging with its claws round his neck, and the jolting, as he went by, had shaken one of its large tail feathers out, and as soon as she had got over her fright, she went and picked it up out of the dusty road. Just as she picked it up, the clatter of feet running along the road came to her ears, and for a moment she feared that the giant had returned; but soon a cow trotted round the bend and stopped at the stream to drink, presently another, and then a third. Each of them took a long look at the Princess, and then bent down its head to
  • 74. take a draught out of the stream. Just then an old man came round the corner, and when he saw the cows had stopped he called out: ‘Gee on, Lightfoot; now, Daisy; come up, Cherry,’ and the cows gave their heads a toss, and walked slowly through the stream. The Princess hurried to one side of the road, for, like many people, she had an instinctive dread of anything like a cow or a bull. The old man noticed it and smiled. ‘Oh, you needn’t be afraid, miss, they won’t hurt you,’ he said; but all the same, she didn’t care to go too near them. ‘They’ve just been frightened by Wopole, King Mumkie’s falconer,’ he went on. ‘Wopole came running round the corner suddenly, and almost knocked Lightfoot—that’s the dun cow—over. He was roaring out “Where is she?” awfully loud. I pity her when he gets her, whoever she is.’ ‘But who is she?’ asked the Princess. ‘I don’t know—how should I?’ ‘Oh, I only thought you might know. But what will he do with her when he gets her?’ ‘I don’t know; fry her in lard or something—that’s what they generally do to strangers in the town now.’ ‘Oh dear!’ said the Princess; ‘how am I to get away from him?’ The old man looked at her curiously. ‘Oh! you’re her,’ he said. ‘I rather think I am. But how am I to get away?’ she answered. ‘If you’ll come with me I’ll take you to my cottage over there, and they’ll never think of looking for you there.’ But the Princess did not exactly like the idea.
  • 75. ‘Aren’t you one of these people?’ she asked; ‘because I don’t relish being fried in lard, or oil, or anything else.’ But the old man shook his head. ‘Good gracious me, no!’ he said. ‘I wouldn’t let them roast the last stranger that came to the town, and so they turned me out.’ ‘Oh,’ said the Princess, ‘then you must be King Abominable.’ ‘I am Abbonamento.’ ‘Then I suppose I shall be safe with you?’ ‘Quite safe, if you like to come; only just help me to drive the cows.’ And the old man called to his animals who were browsing in the grass at the wayside, and they trudged quietly on till they came to a gate in the hedge. This they waited for the old man to open for them, and then went through the meadow until they came to a little farmhouse half hidden by trees. ‘This is my house,’ the King said. ‘Just wait a moment till I have put the cows in the byre, and then I’ll come back and let you in; for you see my wife’s away at the market, and there’s no one else at home.’ So the Princess stopped where she was, and the old man went whistling round to the back of the house driving his cows before him. It was a very small house, with the thatched roof coming so low down that you could touch it almost with your hand, and the windows were quite overshadowed by it. Over a little arbour of trellis-work before the door ran a rose-tree of deep red flowers, and the roses were full of bees that came from the hives arranged on benches under the eaves, and a few chickens were asleep on one leg under the porch.
  • 76. Welcome to our website – the ideal destination for book lovers and knowledge seekers. With a mission to inspire endlessly, we offer a vast collection of books, ranging from classic literary works to specialized publications, self-development books, and children's literature. Each book is a new journey of discovery, expanding knowledge and enriching the soul of the reade Our website is not just a platform for buying books, but a bridge connecting readers to the timeless values of culture and wisdom. With an elegant, user-friendly interface and an intelligent search system, we are committed to providing a quick and convenient shopping experience. Additionally, our special promotions and home delivery services ensure that you save time and fully enjoy the joy of reading. Let us accompany you on the journey of exploring knowledge and personal growth! ebookultra.com