0 ratings0% found this document useful (0 votes) 321 views365 pagesDatabase Access With Visual Basic Net
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
ww
INS
uv
ATU ET MSR
Third Edition
Ge
eH
Real
effrey P. McManus
Jackie Goldstein
Kevin T. Price, ContributorMany ofthe designations used by manufacturers and sellers to distinguish their
products are claimed as trademarks. Where those designations appear in this
‘book, and Addison-Wesley was aware ofa trademark claim, the designations
have been printed with inital capital letters rin all capitals.
“The authors and publisher have taken care in the preparation of this book, but
‘make no expressed or implied warranty of any kind and assume no responsibil-
ity for errors or omissions. No liability is assumed for incidental or consequen-
tial damages in connection with or arising out of the use of the information or
programs contained bercia.
‘The publisher offers discounts on this book when ordered in quantity for balk
purchases and special sales. For more information, please contact:
US. Corporate and Government Sales
800) 382-3419
‘corpaales pearsontechgroup com
For sales outside of the U'S., please contact:
{International Sales
817) 581-3793,
international pearsontechgroup com
Visit Addison-Wesley on the Web: www awprofessional.com
Library of Congress Cataloging-in-Publication Data
McManus, Jeffrey P.
Database access with Visual Basic® Net / Jeffrey P. McManus and Jackie Goldstein;
Kevin T, Price, contrbutor.—3rd ed
». cm.
ISBN 0-672-32343-5 (alk. paper)
1. Microsoft Visual BASIC. 2, BASIC (Computer program language) 3. Microsoft
.NET. I Goldstein Jacke. IL. Price. Kevin T. IIL. Tite.
(QA76.73.B3M3988 2003
005.2764 de21
2002043755
‘Copyright © 2003 by Pearson Education, Inc.
All rights reserved. No par of this publication may be reproduced, stored ina
‘eirieval system, or transmitted, in any form, or by any means, electronic,
‘mechanical, photocopying, reconding, or otherwise, without the prior consent of
‘the publisher. Printed in the United States of America. Published simultaneously
in Canada,
For information on obtaining permission for use of material from this work,
please submit a written request to:
Pearson Eaucatioa, In.
Rights and Contracts Department
75 Arlington Street, Suite 300
Boston, MA 02116
ax: (617) 848-7047
ISBN 0-672.32343.5
‘Text printed on recycled paper
123456789 10—MA—0708050403
First printing, February, 2003Tables and Fields..
Designing Your Database ..
Business Case 1.2: Designing Tables and Relationships
Manipulating Data with Objects
Data Types
Creating a Database Schema.
Using Visual Studio to Create a Database
Designating Indexes and the Primary Key
Creating Database Diagrams
Using Microsoft Visio to View and Alter a Database Schema
Relationships
Using Referential Integrity to Maintain Consistency...
‘Testing Referential Integrity Constraints, Using Server Explorer ...c0..s0a.n 28
Cascading Updates and Cascading Deletes ..
‘Normalization ..
‘One-to-One Relationships
One-to-Many Relationships .n.cswemnnnene se
Many-to-Many Relationships... ¥
Creating a User Interface in a Windows Forms Application 00
Connecting to a Database and Working with Records.
Creating a Data Browser Application.
Performing Binding Programmatically ..
‘About Data-Aware Controls in NET
Updating Records in the Data Browser Application ..
Creating New Records in a Data-Bound Fort ...0onnnonnen
Deleting Records from a Data-Bound Form
Validating Data Entry in a Data-Bound Form
‘Validation at the Database Engine Level
Summary ..
Questions and Answers...
Chapter 2 Structured Query Language Queries and Commands “0
What is a Query:
Testing Queries with the Server Explore
Retrieving Records with the SELECT Clause..a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.‘Using Database Views to Control Access to Data ..
Creating and Running Stored Procedures.
Displaying the Text of an Existing View or Stored Procedure.
Creating Triggers ..
Business Case 3.1: Creating a Trigger That Enables Soundalike
Searches .. .
Managing Users and Security in SQL Server Enterprise
Applying Security Attributes in SQL Query Analyzer.
Removing Objects from the Database
Business Case 3.2: Generating an SQL Script That Creates a
Summary
Questions and Answers
Chapter 4 —ADO.NET—Data Providers 155
ADO.NET Versus Classic ADO (2.x)
ADO.NET Objects Within the NET Framework.
Application Interfaces ... .
Overview of NET Data Provider Objects
sqicrient .
o1edb..
ob.
Core Objects.
The Connection Object
The Comsand Object.
Using the comang Object with Parameters and Stored
Procedures.
Executing the Commands.
The vataReader Object
Using the Connection and Command Design-Time Components
Other Data Provider Objects.
Business Case 4.1: Writing a Routine to Archive Old
Orders by Year ...
Summary
Questions and Answers.
Chapter ADO.NET—The DataSet
Applications and Components of the Dataset.
Populating and Manipulating the Dataset
Defining DataTable Schemas...
Adding Data to a DataTablea
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.xiv
PREFACE
the basics. You may also notice variant coding styles, and even screen shots on different versions
of Windows—all illustrating the flexibility of VB.NET.
Most of the examples in this book are presented with Windows Application (Windows Forms) as
the project type. The reason is that nearly all Visual Basic programmers are most familiar and
comfonable with this type of application. This approach allows us to focus on database access,
rather than on the issues involved in the different types of INET projects. Still, in later chapters,
we do discuss and show ASPNET Web Applications and Web Services, providing database
access examples for these technologies and project types.
How This Book Is Organized
This book can be thought of as containing three parts. The first part, consisting of Chapters 1-3,
comprises the preliminaries. The coverage of database basics, SQL, and SQL Server is meant to
provide the fundamentals required for the novice to proceed comfortably throughout the rest of
the book. At the same time, these chapters provide a good review of these topics even for some-
‘one who is experienced is these areas.
‘The second part can be thought of as the core of the book. Chapters 4-7 provide in-depth expla-
nations and numerous examples of the major ADO.NET objects and the use of their properties
and methods. Chapter 7 goes beyond the basics to explore advanced features and techniques of
the ADO.NET objects.
‘The third part of the book shows how the ADO.NET technologies and techniques previously
presented can be used to build real-world applications. This part includes the use of Visual Stu-
dio Database Projects for managing SQL scripts in Chapter 8, a discussion of XML in Chapter
9, and the integration of XML and ADO.NET in Chapter 10. Finally, we present additional types
of applications that utilize ADO.NET: Chapter 11 covers ASP.NET Web Applications and Chap-
ter 12 covers Web Services and middle-tier objects.
The Software Environment
‘We assume that you have already installed, or are capable of installing, Visual Studio.NET. The
only thing to note regarding its use is that there are significant differences between available
capabilities and behaviors of the visual database tools, depending on the edition of Visual Studio
‘and the type of database that you use. Some of these differences are as follows.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Acknowledgments
As this book comes to life, we would like to thank several people who helped make it happen:
Sondra Scott, our Acquisitions Editor, who got the whole thing started and met many chal-
lenges to keep it going.
Laurie McGuire, our patient and helpful Developmental Editor.
Kevin Price, who agreed to step up and fill in chapters, under difficult circumstances.
Anjani Chittajallu and Andrew Indovina, our Technical Reviewers, who not only kept us
honest, but also provided valuable insights and ideas.
Michael Pizzo, from Microsoft, who always responded immediately to questions, with either
answers or referrals to the right people with the answers.
Our wives, children, families, and friends, who have supported us throughout and make it all
worthwhile,
xixa
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Tables and Fields
‘Charren 1
What Is a Database Platform?
‘The basic functions of a database are provided by a database platform, a software system that
manages how data is stored and retrieved. When using VB.NET, you have a number of data-
base platforms available to you. The primary database platform that we cover in this book is
Microsoft SQL Server 2000. (For an introduction to this database platform, see Chapter 3.) In
contrast, a database engine is the actual workhorse of the database platform. It is the compo-
nent of a database platform actually responsible for executing functions and for data manage-
ment.
Business Cases
Many computer books contain long laundry lists of software features, with hastily scribbled
explanations of how they work. If you're lucky, the discussion of software relates the software
to the real world in some way.
In contrast, in this book we present the software in terms of business solutions. Accordingly,
many of the chapters contain at least one business case, in which a fictional company pursues
the elusive goal of office automation in dealing with common real-world business problems.
Most of the business cases in this book follow the exploits of Jones Novelties, Incorporated, a
small business just breaking into the retail souvenir, novelty, and party-tricks business.
Business Case 1.1: Introducing Jones Novelties, Incorporated
The company’s CEO, Brad Jones, recognizes that, for Jones Novelties, Incorporated, to succeed,
it must automate many of its transactions. These include customer contacts, inventory, and
billing systems, and implementation must be tailored to the business and flexible enough to
‘change over time.
Jones recognizes that the company will rise or fall on the basis of its access to information, so
he decides to use a relational database system to manage the company’s information. The design
and functionality of such a database is the focus of the rest of this chapter.
Tables and Fields
Databases consist of tables, which represent broad categories of data. If you were creating a
database to handle the accounts for a business, for example, you might create one table for cus-
tomers, another for invoices, and another for employees. Tables have predefined structures con-
taining data that fits into them.
‘Tables contain records, which are individual pieces of data within a broad category. For
‘example, a table of customers contains information pertinent to the people that make up the
client base of a business. Records can contain almost any type of data and are retrieved, edited,
mm
oda
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Manipulating Data with Objects [>
CuapreR Do
Note how the database developer named the tables and fields in her preliminary table designs. 1
First, she named each table with the prefix 1b/. Doing so enables her to distinguish, at a glance, a
table from another type of database object that can also store records. Next, note that each field
‘name consists of full words (instead of abbreviations) and doesn’t contain spaces or other spe-
cial characters such as underscores.
Although SQL Server enables you to name database objects with spaces, underscores, and
other nonalphanumeric characters, it’s a good idea to avoid their use. Using them makes it diffi-
cult to remember the exact spelling of a field name later. (You won't have to remember whether
the field is named FirstName or FIRST_NAME, for example.) Although this guideline seems
like a trivial distinction now, when you start writing code against a database consisting of 50
tables and 300 fields, you'll appreciate having named things simply and consistently from the
beginning.
‘One last thing missing from Jones's wish list is the answer to the question, When did this cus-
tomer last purchase something from us? The database developer decides that this information
can be determined from date values in the table that stores data pertaining to customers’ orders.
This table has the following structure.
‘Solsvg asveviva
In this table, the ID field uniquely identifies each order. The CustomerID field connects an order
with a customer. To attach an order to a customer, the customer's ID is copied into the Order
table’s CustomerID field. That way, looking up all the orders for a particular customer is easy
(as we demonstrate later).
Manipulating Data with Objects
‘Once you have created tables, you'll need a way to manipulate them. That involves entering data
into tables and retrieving data from them, as well as inspecting and modifying the structure of
tables. To manipulate the structure of a table, use data-definition commands (covered in Chapter
2). To manipulate data, use one of two objects provided by the .NET framework: DataSet or
DataReader.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Creating a Database Schema
CHAPTER 1
Using Visual Studio to Create a Database
‘There are a number of ways to create a database in SQL Server. It has its own set of tools,
known as SQL Enterprise Manager, which enables you to create databases and tables graphi-
cally or programmatically (using SQL commands). Available are a number of external tools
that enable you to work with database structures (one of which, Visio, is described later in this
chapter).
Visual Studio.NET has an outstanding facility for working with a SQL Server database. This
facility is contained in Server Explorer, a new Visual Studio feature that lets you work with all
kinds of server software in an integrated way. To use Server Explorer to create a SQL Server
database do the following.
1, Launch VS.NET.
2. From the left side of the VS.NET window, select the Server Explorer tab. The Server
Explorer window appears. (Note that tabs to select Server Explorer may be vertical or
horizontal.)
3. Expand the outline so that you can see your server from the Servers node. Beneath your
server name should be a SQL Servers node. Expand it to see the instance of SQL Server
running on your machine, as shown in Figure 1.1.
Figure 1.1. The Server Explorer window in Visual Studio.NET. In this window, you can manage server
processes, such as SOL Server.
"
eeea
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Creating a Database Schema |<
2. A property page appears with a list of existing indexes. The primary key index (called
PK_tbICustomer) should already be there. Click on the New button to create a new index
for the FirstName field.
3. In the list of column names, choose FirstName (as shown in Figure 1.3), then click on Close.
4. Repeat this process for the LastName field.
Figure 1.3 The Table Structure dialog box, after all the fields and indexes have been designated
Copyrighted materiala
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.ri spt at
Figure 1.7 The database diagram for the Novelty database, denoting a relationship between
1tbiCustomer and thlOrder
It’s particularly useful that SQL Server creates and stores the database diagram within the data-
base itself. Thus you can always get to the diagram, even from different tools. (You can manipu-
late database diagrams in SQL Enterprise Manager, as well as in VS.NET.)
Using Microsoft Visio to View and Alter a
Database Schema
‘You may find it useful to use a graphical tool other than VS.NET to create, inspect, and modify
database schemas. The diagramming tool Microsoft Visio has the capability to diagram database
‘structures automatically; it can also easily reverse engineer nearly any kind of existing database
‘structure. This capability makes this tool particularly useful for documenting and working with
the database schemas of databases that were designed in the mists of time by programmers
unknown.
Note
It isn’t strictly necessary for you to know how to use Visio to set up a SQL Server data-
base. It’s just a different way of rolling database design and documentation tasks into
a single set of operations. if you feel comfortable using Visual Studio's Server Explorer
(or SQL Server’s own Enterprise Manager tools), or if you don't have access to the
version of Visio that comes with Visual Studio Enterprise Architect, you can safely skip
this section,
soisvg asvavivaa
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Creating Database Diagrams | 53
(CHAPTER 1
2. Right-click on the entity shape that you just created and then select Database Properties
from the pop-up menu. A Database Properties sheet appears at the bottom of the Visio
window.
3. Type the name of the table, tblRegion, into the Physical Name field.
4, In the list of Categories in the Database Properties sheet, click on Columns. Create the
three fields in the table definition by typing them into the grid. Note that, to denote the
length of the char and varchar fields in the table, you must select the field and click on the
Egit button on the right side of the property sheet.
‘When you're done, the graphic should look like Figure 1.10.
Para
Copyrighted materia
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Relationships |
Caarrer 1
Note
Don't confuse the process of developing a database schema with a software design
methodology. Most successful software development organizations have a design
methodology in place that dictates what business problems the software is supposed
to solve, how the software application will look, how it will be built, and the like. You
should consider all these issues before you design a database.
Relationships
A relationship is a way of formally defining how two tables relate to each other. When you
define a relationship, you are telling the database engine which two fields in two related tables
are joined.
‘The two fields involved in a relationship are the primary key, introduced earlier in this chapter,
and the foreign key. The foreign key is the key in the related table that stores a copy of the pri-
mary key of the main table,
For example, suppose that you have tables for departments and employees. There is a one-to-
many relationship between a department and a group of employees. Every department has its
‘own ID, as does each employee. In order to denote which department an employee works in,
however, you must copy the departments ID into each employee’s record. So, to identify each
‘employee as a member of a department, the Employees table must have a field—say, Depart-
mentld—to store the ID of the department to which that employee belongs. The DepartmentID
field in the Employees table is referred to as the foreign key of the Employees table, because it
stores a copy of the primary key of the Departments table.
A relationship, then, tells the database engine which two tables are involved and which foreign
key is related to which primary key. The old Access/JET engine doesn’t require that you explic-
itly declare relationships, but it's advantageous for you to do so. The reason is that it simplifies
the task of retrieving data based on records joined across two or more tables (discussed in more
detail in Chapter 2). This lack of declaration is one of the major weaknesses of the JET tech-
nology and by far a good reason to upgrade any legacy applications still JET to use
ADO.NET. In addition to matching related records in separate tables, you also need to define a
relationship to take advantage of referential integrity, a database engine property that keeps data
in a multitable database consistent. When referential integrity exists in a database, the database
‘engine prevents you from removing a record when other records are related to that record in the
database.
27
soisvg asveviva, |a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book._Normalization
eT
2. Create a customer by right-clicking on tbiCustomer in the Tables folder and then selecting
Retrieve Data from Table from the pop-up menu. Note the ID that the database engine
assigns to the newly created customer; you'll need it shortly when you create orders for
this customer. Leave this table open because you'll be returning to it in a moment.
3. Open the tblOrder table and create two or three order records for the customer you just
created, To relate each order to the customer, enter the customer's ID in the CustomerID
field. Leave this table open as well.
4. Go back to the tbiCustomer data-entry grid and delete the customer record by right-
clicking on the gray row selector on the far left side of the row and then choosing Delete
from the pop-up menu,
5. Visual Studio.NET displays a warning message asking you if you really want to delete the
data, Answer Yes.
6. Go back to the tblOrder window. Whoops, you probably expected that the orders you
entered for this customer would have been deleted. But they're still there—what
happened? Actually, they were deleted; you're just looking at an outdated view of the
data. To refresh the data, select the menu command Query, Run. The data-entry grid re-
freshes itself by refetching the data from the database, revealing that the order records for
the customer you deleted were automatically deleted thanks to the magic of cascading.
Normalization
Normalization is related conceptually to relationships. Basically, normalization dictates that
your database tables eliminate inconsistencies and minimize inefficiency.
Recall that databases are called inconsistent when data in one table doesn’t match data in an-
other table. For example, if half your staff thinks that Arkansas is in the Midwest and the other
half thinks it’s in the South—and if both factions handle data entry accordingly—your database
reports on how things are doing in the Midwest will be meaningless.
An inefficient database doesn't allow you to isolate the exact data you want. A database in which
all the data is stored in one table might force you to slog through myriad customer names, ad-
dresses, and contact histories just to retrieve one person’s current phone number. In contrast, in
a fully normalized database each piece of information in the database is stored in its own table
and is identified uniquely by its own primary key. Normalized databases allow you to reference
any piece of information in any table if you know that information's primary key.
‘You decide how to normalize a database when you design and initially set it up. Usually, every-
thing about your database application—from table design to query design and from the user
interface to the behavior of reports—stems from the way you've normalized your database.
31
sosvg asvaviva |a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Normalization
Charren 1
‘we created earlier, there's a one-to-many relationship between customers and orders. Because
each customer can have none, one, or many orders, we say that a one-to-many relationship ex-
ists between tbICustomer and tblOrder.
Recall that, to implement this kind of relationship in a database design, you copy the primary
key of the “one” side of the relationship to the table that stores the “many” side of the relation-
ship. In a data-driven user interface, this type of relationship is often represented in a master/
detail form, in which a single (“master”) record is displayed with related (“detail”) records
displayed in a compact grid beneath them. In a user-interface design, you'll usually copy the
primary key of one table to the foreign key of a related table with a list box or combo box.
Many-to-Many Relationships
‘A many-to-many relationship takes the one-to-many relationship a step farther, The classic
example of a many-to-many relationship is the relationship between students and classes. Each
‘student can have multiple classes, and each class has multiple students. (Of course, it's also
possible for a class to have one or no students, and it’s possible for a student to have one or no
classes.)
In our business example, there's a relationship between orders and items. Each order can com-
prise many items, and each item can appear on many orders.
To set up a many-to-many relationship, you must have three tables: the two tables that store the
actual data and a third table, called a juncture table, that stores the relationship between the two
data tables. The juncture table usually consists of nothing more than two foreign keys—one
from each related table—although sometimes it’s useful for the juncture table to have an
identity field of its own in case you need to access a record in the table programmatically.
‘An example of a many-to-many relationship is to configure the business database to store
‘multiple items per order, Each order can have multiple items, and each item can belong to an
unlimited number of orders. These tables would look like those shown in Figure 1.13.
Description
Figure 1.13 Tables involved in a many-to-many relationship. In this design, blOrderliem is the
juncture table.
35
ela
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.(Creating a User Interface in a Windows Forms Application [~~ 35 |
CHarrER 1 J
5. Bind the text box txtLastName to the database field LastName the same way you bound
txtFirstName.
6. Run the application, The first and last name of the first customer should appear.
This application is limited—at this point, you can view only a single record, and once again,
you can’t change data or create new customer records. But this application is a good start. We
build on it in the next few demonstrations, adding capabilities that transform the simple data
browser into a real database application with the ability to manipulate data.
Even though this application isn’t complete yet, you can already see the power of data binding
in NET—it's much more flexible and granular than the data-binding options provided in VB6.
For example, the ability to manage the process of binding entirely in code offers a great deal of
flexibility.
Next you'll need to add code to enable you to navigate from one record to the next. To do so, do
the following.
1. Create two buttons on the form, one called binPrevious and the other called binNext.
2. Double-click on btnNext to expose its Click event procedure definition. Insert the follow-
ing code for this event procedure.
Private Sub btnNext_Click(ByVal sender As Object, _
ByVal @ As EventArgs) Handles btnNext.Click
Me.BindingContext(DsCustomert, “tblCustoner").Position += 1
End sub
3. In the Click event procedure for binPrevious, write the following code.
Private Sub btnPrevious Click(ByVal sender As Object, _
Byval e As EventArgs) Handles _
btnPrevious.click
Me.BindingContext(DsCustomert, *tblCustomer*) .Position= 1
End Sub
4. Run the application again. You should be able to move backward and forward through the
customer table, one record at a time. (Note that this procedure will work only if you have
‘more than one customer record in the table.)
‘The BindingContext object provides navigational capabilities for a data-bound application. If
you've created data-bound applications in previous versions of Visual Basic, you know that the
Data control was responsible for navigating from one record to the next. In the .NET frame-
work, however, the BindingContext object has been factored out of the process of data binding.
(Put simply, factoring out an object entails taking one large object and breaking its functionality
into two or more simpler objects.) In object design, a software designer typically factors outa
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Creating a User Interface in a Windows Forms Applicat
CHarre
stored persistently until you explicitly tell the Dataset to do so (by calling the Dataset’s Up- 1
date method). Although this instruction might seem like a needless extra step (you never had to
do it with the data controls provided by previous versions of Visual Basic), it's actually a power-
ful feature of NET. Why? Because you don’t need to update until it's appropriate to do so—and
while the user is editing data, the application doesn’t maintain a connection to the database.
soisyg asvavivg
Listing 1.2 shows a pair of modified event procedures that enable editing in the data browser
application.
Listing 1.2 saving data by updating the Dataset object as the user navigates in the
data browser application
Private Sub btnNext_Click(ByVal sender As Object, ByVal e As EventArgs) _
Handles btnNext.click
Me. BindingContext (DsCustomert, *tb1Custome:
‘SqlDataAdapter .Update(DsCustomert)
ShowOataStatus()
End Sub
Position += 1
Private Sub btnPrevious_Click(ByVal sender As Object, ByVal e As _
EventArgs) Handles btnPrevious.Click
Me.BindingContext (DsCustomer1, “tbiCustoner™
‘SqlDataAdaptert .Update (DsCustomer1)
Showatastatus()
End Sub
Position = 1
Of course, updating each record as the user navigates from one record to the next isn't necessary.
Because you have programmatic control of when the Dataset is updated, you could instead
‘choose to commit changes back to the database when a user clicks a Save button or menu com-
mand. Or you can put off updating entirely until several records have been changed—this proce-
dure is known as batch updating. In ADO.NET writing extra code to perform batch updates isn’t
necessary. I's all handled by the DataSet object (which stores the data in memory) and the $0.
DataAdapter object (which is responsible for performing the necessary database commands to
‘ensure that the correct view of data is displayed and that data is inserted, updated, and deleted
properly). We consider further the relationship between these objects in Chapters 5 and 6.
Creating New Records in a Data-Bound Form
‘To create a new record in a data-bound Windows Forms application, use the AddNew method of
the form's BindingContext object. When you execute this method, any bound controls are
cleared, allowing new data to be entered. When new data has been entered, you commit the new
record back to the database by executing the Update method of the DataAdapter object (as in
the preceding example).a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.‘Summary
es — mt
more work for the database, offsetting the benefit provided. As you go through the next few
chapters and consider the business cases presented, keep these points in mind,
Questions and Answers
Q: In VB6 I built quick data prototypes using the data control. Is there a data control in
VS.NET?
A: No. All the functionality of the data control from VB6 and previous has been factored into
the various data objects that we discussed in this chapter. For example, the ability of a data
control to connect to a database is now handled by the SqlConnection object. The data con-
trol’s ability to retrieve, update, and delete records is managed by the BindingContext object,
in conjunction with the OataAdapter object. Navigating from one object to the next is the
responsibility of the BindingContext object, and so on. Unlike the old data controls, none of
these objects have any visual representation at run time, which works to your advantage,
enabling you to build whichever kind of data-driven user interface you want.
Q: Is it possible to have a primary key comprise more than one field?
A: Yes. Although not often done, in the database environment, it is known as a concatenated
key. For example, you might use such a key if you know that all the people in your database
are going to have a unique combination of first and last names. You choose to make the First-
Name and LastName fields the concatenated primary key so that users can never enter the
‘same name twice in the database.
47
‘soisvg asvavivg, |a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.| 52 Structured Query Language Queries and Commands
CHarren 2
Figure 2.1. The View Design window
Note
You may have noticed that we use a naming convention for tables, views, and the like
that attaches a prefix (such as tbl or qry) to the names of objects in the database. We
do so for two reasons: (1) it makes it easy for you to figure out what kind of object
you're dealing with in situations where that may not be clear—tables and views, for
example, can behave nearly identically in many cases; and (2) we used this convention
in previous editions of this book and wanted to stay consistent with those earlier
editions.
Our convention will be familiar to Microsoft Access programmers in particular.
Although we're doing things a little differently than SQL Server programmers might
be accustomed to, we figured that adhering to some naming convention was better
than not having one at all. Of course, in your work, you're welcome to name things
however you want.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Structured Query Language Queries and Commands
Charter 2
This query retrieves the record for the customer who lives in California, Daisy Klein.
Note also that the delimiter for a text string in a WHERE clause is a single quotation mark. This
marker is convenient, as you'll see later, because the delimiter for a string in VB.NET is a
double quotation mark, and SQL statements must sometimes be embedded in VB code.
‘You can create more sophisticated WHERE clauses by linking two or more criteria with ANO and OR
logic. For example, say that you want to retrieve all the customers who live in Denver, Colorado
(as opposed to those customers who live in other cities in Colorado). To do so, you need to de-
note two criteria linked with an ANO operator:
SELECT FirstName, LastName, City, State
FROM — dbo. tbiCustoner
WHERE (State = 'CO') AND (City = ‘Denver')
Hypothetically, running this query should retrieve Thurston Ryan, the customer who lives in
Denver, Colorado. If you had more than one customer in Denver, Colorado, they'd all be re-
trieved by this query. However, it wouldn’t retrieve any customers who live in a city named
Denver in some state other than Colorado (assuming that such a place actually exists).
If you're interested in seeing information on people who live in two states—for example, both
Colorado and California—use an of clause to link the two criteria, as in
SELECT FirstName, LastName, City, State
FROM tbiCust
WHERE State='CO' OR State='CA"
Running this query retrieves the three records from tbICustomer who live in California or Col-
orado. As these examples clearly show, you can go nuts trying to link WHERE criteria with AND
and OR conditions to extract data from a table.
Note
One key to successful database development is to keep client applications from re-
ing too many records at once. Doing so will ensure that your applications run
quickly and won't do bad things such as causing users’ computers to run out of mem-
ory. One of the most basic weapons that you can use to avoid these unfortunate re-
sults is the WHERE clause.
Operators in WHERE Clauses
You can use the operators listed in Table 2.1 to construct a WHERE clause. The equality and ine-
quality operators work exactly the same way in SQL as they do in VB.NET.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Structured Query Language Queries and Commands
Charen 2
SELECT FirstName, LastName, City, State
FROM tblCustomer
ORDER BY LastName, FirstName
This query retrieves all customers from the database. Unlike our earlier customer query, the two
customers whose last names are identical (Betty Klein and Daisy Klein) are sorted correctly this time.
Displaying the Top or Bottom of a Range with TOP
The To? keyword displays only the top or bottom few records in a large record set. In queries,
TOP is combined with a SORT clause to limit the number of records to a set number of records or
4 percentage of records in the result set.
For example, say that you want to view the three most recent outstanding orders in tblOrder. To
do so, start by writing a SQL statement such as
SELECT ID, OrderDa
FROM tblorder
ORDER BY OrderDate DESC
CustomerID
‘The DESC keyword causes the result set to be sorted in descending (biggest to smallest) order.
This query retrieves all the orders in tblOrder by customer, with the most recent order first and
the earliest order last. This result is fine, except that in a database that stores every order
received, you might have to sort thousands of records when all you're really interested in are the
last three outstanding orders. So instead, try the SQL statement
SELECT TOP 3 *
FROM tblOrder
ORDER BY OrderAnount DESC
This query retrieves the three records in tblOrder with the most recent order dates.
Note that, although you asked for three records, you're not guaranteed that only three records
will be returned in this query. With a ToP W query, none, one, or two records may be returned if
your table has only that many records. And if two or more records are tied for last place in your
result list, four or more records may be returned.
There is no such thing as “BOTTOM N” in SQL syntax, but you can return the last few records
in a table—in this case, the most recent orders in your system. To create such a query, simply
order the records by most recent date:
SELECT TOP 3 *
FROW tblOrder
ORDER BY OrderDate
This query retrieves three records representing the three most recent orders in your databasea
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.b
ebicustoner
eblorder
<<<
tb TGus tomer.Las tName,
SELECT dbo. tb!customer.Firstwane, di
dbo. thlorder. Orderoate
IFRom dbo. ebicustomer INNER JOIN
dbo. telorder cn dbo.tbicustomer. 10 = dbo. tbl0rder.customerI0
Smith 1/9/2001
pa11azaia 471672001
patsy Teta 2/18/2001
patsy klein 3/21/2001
joaisy klein 4/4/2001
[pave martin 6/5/2001,
|Ethurston Ryan 7/2/2001
[Ejsane winters 8/16/2001,
[vane winters 9/10/2001
Figure 2.6 A joined query in the View Designer window after it has returned data
Running the query returns data based on the relationship between customers and orders, as
shown in Figure 2.6.
Using Outer Joins to Return Additional Data
A conventional join returns records from two tables in which a value in one table’s primary key
matches a value in a related table’s foreign key. But suppose that you want to return all the rec-
cords on one side of a join whether or not there are related records? In this case, you must use ana
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.68
Structured Query Language Queries and Commands
(Cuarrer 2
Aggregate queries summarize data according to one or more fields in common. For example, if
you wanted to see how many orders have been placed by each customer, you'd perform a query
(on tblOrder grouping on the CustomerID field. The following is an example of such a query:
SELECT CustomerID, COUNT(CustomerID) AS TotalOrders
FROM tblOrder
GROUP BY CustomerID
A similar result set is produced by this query.
Note the use of the AS clause in the SQL expression. This clause is used to give the column
containing the result of the aggregate function a name because it's calculated rather than stored
in the database.
To display customer names instead of IDs, simply join data from tbICustomer, as in
SELECT tblOrder.CustomerID, FirstName, LastName,
COUNT (dbo. tblOrder.CustomerID) AS TotalOrders
FROM tblOrder INNER JOIN tblCustomer
ON tblOrder.CustomerID = tb1Customer. 10
GROUP BY FirstName, LastName, CustomerID
A similar result set is produced by this query.
CustomerID FirstName LastName ___TotalOrders
1 John ‘Smith 2
2 Jill Azalia 1
4 Daisy Klein 3
5 Dave Martin 1
7 Thurston Ryan 1
8 Jane Winters 2a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Structured Query Language Queries and Commands
Carrer 2
Union Queries
‘A union query merges the contents of two tables that have similar field structures. It's useful in
situations in which you need to display potentially unrelated records from multiple record
sources in a single result set.
Later in this chapter, we describe a way to store old orders in a table of their own, called
tblOrderArchive, Because of the way this archiving system is set up, the records are physically
located in two separate tables. This approach might be useful for efficiency, as it’s usually faster
to query a small table than a large one. But at some point you may want to view all the current
records and the archived records in a single, unified result set. A union query lets you do so.
‘Suppose that you need to view the old records in tblOrderArchive in the same result set as the
new records in tblOrder. The union query you write to accomplish that is
SELECT *
FROM tblOrder
UNION
SELECT *
FROM tblOrderArchive
The result set of this query combines old and new orders in a single result set. The output looks
exactly like the original table before it was archived.
By default, union queries don’t retum duplicate records (that is, records with the exact same
field contents from each of the two tables). Displaying duplicate records might be useful if your
record archiving system didn't delete records after it copied them to the archive table and you
wanted to display some sort of before-and-after comparison.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.‘Structured Query Language Queries and Commands
Charter 2
16 |
DELETE *
FROM tblOrder
WHERE OrderDate < '10/31/98'
Insert Commands
An insert command is used for two purposes:
1. Adding a single record to a table
2. Copying one or more records from one table to another
To create an append query, use the SQL INSERT clause, The exact syntax of the query depends
‘on whether you're inserting a single record or copying multiple records. For example, a single-
record append query that adds a new order to tblOrder might look like this:
INSERT INTO tblOrder (CustomerID, OrderDate)
VALUES (119, '6/16/2001')
Executing this query creates a new order for Customer 119, dated June 16, 2001, in tblOrder.
In this update command, you don’t append anything for tblOrder's ID field because it
is an identity column. Attempting to do so would generate an error. In general, only
the database engine itself can alter the contents of an identity column.
To create the kind of insert command that copies records from one table to another, use an IN-
SEAT clause in conjunction with a SELECT clause. For example, say that, instead of deleting old
orders, you want to archive them by periodically copying them to an archive table called
tblOrderArchive, which has the same structure as the tblOrder table. For that to work, you'll first
need to create tblOrderArchive with an SQL command:
CREATE TABLE tblOrderArchive (
ID [int] NOT NULL ,
CustomerID [int] NULL ,
OrderDate {datetime} NULL
Note
SQL commands that create and otherwise manipulate the structure of a database are
called SQL Data Manipulation Language commands. We cover SQL DML later in this
chapter.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Structured Query Language Queries and Commands
Charrer 2
Note that designating a foreign key in a CREATE TABLE command doesn't create an index on that
foreign key; it serves only to create a relationship between the two tables.
Creating Indexes with CREATE INDEX
In addition to creating indexes when you create your table (using the CONSTRAINT clause), you
can also create indexes after you've created the table (using the CREATE INDEX clause). This
approach is useful when you want to create an index on a table that already exists (as opposed to
the CONSTRAINT clause, which lets you create indexes only on tables when you create the table).
‘To create an index on an existing table, use
CREATE INDEX StateIndex
ON tbicustomer ((State])
To create a unique index, use the UNIQUE keyword, as in
CREATE UNIQUE INDEX StateIndex
ON tblRegion ([State])
To create a primary key on an existing table, use
CREATE UNIQUE NONCLUSTERED INDEX StateIndex ON dbo.tb1Region
(
State
) ON [PRIMARY]
Deleting Tables and Indexes with DROP
You can delete database elements by using the DROP clause. For example, to delete tblRegion,
use
DROP TABLE tblRegion
‘You can also drop an index in a table by using the DROP clause:
USE Novelty
IF EXISTS (SELECT name FROM sysindexes
WHERE name = ‘StateIndex')
DROP INDEX tblRegion.StateIndex
eo
Note that, to delete a primary key, you must know the primary key’s name,
To drop individual fields from tables, use a DROP clause within an ALTER TABLE clause, as dis-
cussed in the next section. Finally, to delete an entire database, use the DROP DATABASE clause.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.|_ Getting Started with SQL Server 2000
CuapTer 3
In the past, many Visual Basic programmers got their first exposure to database programming
through the Jet database engine shared by Visual Basic and Microsoft Access. As soon as data-
base applications grew beyond a few hundred records or a few users, programmers commonly
ran into limitations. Multiuser contention for data, poor performance, and lack of advanced data
and server-management features caused many programmers to turn to an alternative architecture
to resolve their database problems. That architecture is client-server (or distributed) computing.
Client-server computing is not to be confused with multiuser computing, which Jet supports just
fine. In a multiuser architecture, a number of users share the same data over a network. That is,
the database file or files reside on a central server, which all the user workstations can access.
The key is that in an architecture such as Jet, which is not a client-server architecture, all the
processing is done on the client workstations. That is, in order to retrieve a single row defined by
an SQL. SELECT statement from a table containing 50,000 rows, all the rows (or at least their
indexes) must first be transferred to the client workstation. No intelligence exists on the other
side of the network that can process requests and returning data.
However, client-server architecture has some sort of back end—not the body part of a program-
‘mer who sits in a chair for 18 hours a day but rather a piece of software responsible for retrieving
and caching data, arbitrating contention between multiple users, and handling security. This soft-
ware, Microsoft SQL Server, for example, receives requests from client workstations, executes
the requests on the server computer, and then returns only the results to the client machine. Thus,
in the case of requesting a single row from a table with 50,000 rows of data, the SELECT statement
is transferred to the server, the server’s database software executes the statement and then returns
the single row to the client. The savings in network traffic is obvious; another performance benefit
is that server machines are usually stronger (that is, faster CPUs and more memory) than client
‘machines, so the actual statement execution and retrieval of the data are faster.
If you're using Visual Basic. NET (VB.NET), Microsoft SQL Server is your obvious choice for a
database back end. Not only is it a powerful and easy-to-use database system, but a copy of SQL
Server also is included with every edition of VB.NET and Visual Studio.NET (VS.NET). We
clarify which editions of SQL Server are included with which editions of VB.NET and VS.NET,
after describing the different SQL Server editions.
Tie
You should avoid using Jet (MDB) databases in anything but the simplest or most
memory-limited applications. Introduction of SQL Server 2000 Desktop Engine (MSDE)
eliminates the need to use Jet databases for prototyping and/or low-cost systems. By
using a freely distributable, SQL Server-compatible database right from the start, you
will never need to make query, code, or design changes when your system needs to
“grow up.”a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Getting Started with SQL Server 2000 _
‘CHAPTER 3
Installing SQL Server 2000
After you've designated a computer for use with SQL Server, you can proceed wit
Itis fairly straightforward, with a few minor exceptions.
installation.
+ Ittakes a long time.
* It asks you a lot of weird questions that most conventional applications don’t ask.
‘We can’t help you with the fact that it takes a long time, but we can give you some pointers
about the questions posed by SQL Server's setup application.
In general, and certainly for simple developmental configurations, you should accept the default
options that are offered by the dialog pages of the setup wizard. The following comments refer
to the dialogs that require a bit more thought.
In the Setup Type dialog box shown in Figure 3.1, you get to choose among typical, minimum,
and custom setups, as well as the paths to the folders for the SQL Server programs and data
files. Be sure that you have enough disk space on the drive where you store the data files and
that they are on a path that is regularly backed up.
In the Services Accounts dialog shown in Figure 3.2, the default is a Domain User account, but
you may want to use the Local System account if you aren’t on a domain or have your own
dedicated development server machine. On this dialog page you can determine whether SQL
Server should start automatically when Windows is started. If you select this option, bear in
mind that SQL Server will be started as a service from Windows. Services Accounts act as if
they're part of the operating system; they don’t appear in the Task Manager, and they can’t be
shut down like normal applications can. In the next section we give more information on how to
hk rye Seg yous, an ch Nat
© [fal rte othe mont canner pre Recommend rot er
© ty rad th neem ened tent
"Younay chore coer yours tal Reconnera s
C Bam recedes ™
Figure 3.1 Setup Type dialog box of the SQL Server Installation Wizarda
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.lo | Getting Started with SQL Server 2000 —
Charter 3
Note
Starting and stopping SQL Server by using the Services control panel is essentially the
same as starting and stopping it from the SQL Service Manager, albeit less colorful.
Getting Started with SQL Server 2000: The Basics
After installing it, you have several minimum tasks to complete before SQL Server begins stor-
ing and retrieving data, including:
+ Creating one or more databases
* Creating tables in a database
*+ Creating views and stored procedures that govern how data is retrieved from a database
+ Setting up user accounts and security groups
All the tasks you need to perform are described in this section. Most can be handled without
writing code by using the SQL Server Enterprise Manager utility in SQL Server 2000.
Running SQL Server Enterprise Manager
‘You can perform many of the most common database configuration and setup tasks in SQL
Server by using a utility called SQL Server Enterprise Manager. Because of its power and ease
of use, SQL Server Enterprise Manager is one of the most important tools in Microsoft SQL
Server 2000. The utility makes the database administrator's task easier by putting an easy-to-use
graphical interface on top of a number of chores that were formerly accomplished (and can still
be accomplished) with somewhat arcane SQL commands.
You launch Enterprise Manager from its icon in your Microsoft SQL Server program group.
After you've launched it, you'll gain access to the SQL Server(s) available on your network. The
following sections in this chapter describe some of the most common tasks you will perform
with Enterprise Manager in a production application.
Note
Jn a new SQL Server installation, you have only one username, sa, and it has no pass-
word. You'll obviously want to change this situation soon because a username without
2 password is like a bank vault without a lock. For more information on how to man-
age user accounts and security in SQL Server, see the Managing Users and Security in
SQL Server Enterprise Manager section later in this chapter.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.Figure 3.8 The Data Files tab of the Database Properties dialog box allows specification of file loca-
tion and growth properties.
ten a
Unlike earlier versions of MS SQL Server, there is no need to predetermine and allo-
cate the size of the data and log files. SQL Server 2000 allows for automatic growth of
the files as necestary, in increments of ether «fixed numberof megabytes
Serene Sena Se fis os Vou soe oer nessa mice as treo
doesn’t grow uncontrolled until the entire hard disk is full.
5. Click on OK. On the hard disk drive, two new files have been created—Novelty_Data.mdf
and Novelty_Log.ldf—each with the default initial size of 1 MB.
6. ‘The new database is created and the Database Properties dialog box closes. The new
database should appear in the Databases folder of the Microsoft SQL Servers console
window.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.100
Getting Started with SQL. Server 2000
‘Charter 3
9, When you've finished designing the table, click on the Save button on the toolbar at the
top of the dialog box.
10. The Choose Name dialog appears. Type the table’s name in the box, then click on OK.
‘You can use nearly any name you want, but for the examples in this chapter, we use the
table name thiCustomer.
11, The newly created table should appear in the Microsoft SQL Servers console window.
Creating an Identity Column to Uniquely Identify Records
It is useful (although not required) for every record to have a piece of information that uniquely
identifies it. Often, this unique identifier has nothing intrinsically to do with the data represented
by the record. In SQL Server, a column can be defined to be an identity column (analogous to
the concept in Jet of an AutoNumber field). An identity column automatically assigns a
numeric value to a column in each record as the record is created.
If you're familiar with Jet’s AutoNumber field, it is useful to contrast it to SQL Server's identity
column. A SQL Server identity column is different from, and in some ways more flexible than, a
Jet AutoNumber field. Identity columns in SQL Server have the following attributes.
* They can be of any numeric data type (in Jet, they can only be long integers).
‘+ They can increment themselves by any amount you specify (in Jet, they can only increment
themselves by 1—or a random amount).
+ They can start numbering at any value you specify (in Jet, they always begin at 1).
* They can be overridden, This feature allows you to insert specific numbers into identity
columns—to reconstruct a record that was accidentally deleted, for example. (In Jet,
identity columns are always read-only.)
A SQL Server identity column is less flexible than a Jet AutoNumber field in one respect: If
you're going to create an identity column for a table, you must do it when you create the table
(before adding any data). The reason is that SQL Server requires that any field created later must
allow null values; again, non-null fields can only be created before the table contains any data.
To create an identity column using SQL Server Enterprise Manager, follow these steps.
1. In the Design Table dialog box, create a new field called ID. Make its data type int. Re-
member that the SQL Server int data type is four bytes long, just like the Visual
Basic.NET Integer data type.
2. Uncheck the Allow Nulls box. Doing so ensures that null values can’t be inserted into this
column; it also makes this column eligible to act as an identity column.
3. The bottom portion of the Design Table dialog box displays a property page for the prop-
erties of the currently selected column in the table. Click on (or tab to) the Identity field in
the property page.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.104 |
Getting Started with SQL Server 2000
Charter 3
To issue commands to the database by using SQL Query Analyzer, launch SQL Query Analyzer
from the Microsoft SQL Server program group (or the Tools menu of the SQL Server Enterprise
Manager). SQL Query Analyzer displays the Connect to SQL Server dialog box. Then choose
the server you want to connect to, type in a username and password, and click on Connect. The
SQL Query Analyzer main window appears, as illustrated in Figure 3.13. When commands are
executed, an additional multitab pane is added to display results, messages, and various statistics
and plans. We present the results and messages tabs in later examples in this chapter.
Once you've launched SQL Query Analyzer, you can begin issuing commands to the database in
‘SQL. To be sure it’s working properly, though, test the connection to the database before at-
tempting to do anything else. You can do so with the pubs database that ships with SQL Server,
as follows.
1. Tell SQL Server which database you want to use by executing the SQL USE command,
followed by the name of the database you want to use. In SQL Query Analyzer’s Query
window, type
USE pubs
Figure 3.13 The main window of SOL Query Analyzera
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.108
Getting Started with SQL Server 2000
Chaerer 3
Remember, if you forget the name of a database (or its spelling), you can look it up in SQL
Enterprise Manager or list the available databases using the sp_helpab stored procedure, which
returns information about a specified database or all databases.
Issuing SQL Commands to SQL Query Analyzer
‘You can execute any type of SQL command against a database by using SQL Query Analyzer,
which has some advantages over other methods of sending commands to SQL Server. Remem-
bering SQL syntax can be more difficult than using SQL Enterprise Manager—particularly
when you're using seldom-executed commands such as those for creating databases—but SQL
Query Analyzer has the advantage of being interactive. The utility responds immediately to
commands you issue. SQL Query Analyzer also has a number of features not offered by SQL
Enterprise Manager, such as the capability to run queries and stored procedures.
In Chapter 2 we discussed the syntax of most of the basic SQL commands you're ever going to
‘want to issue against a relational database. Most of this information is also applicable to running
queries and creating database structures in SQL Server.
Using Database Views to Control Access to Data
A view is a query definition stored in a database. It is conceptually similar to a query definition
in the Microsoft Jet database engine, in the sense that it is a stored definition that resides in the
database and gives client applications access to data.
‘You use views in situations when you want to give users access to data but don’t want to give
them direct access to the underlying tables. However, once defined, views can be thought of as
virtual tables and used whenever a database table would be used. The fact that a view looks
exactly like a table to a client application gives you a number of advantages. For example, when
users access data through views rather than through direct access to tables:
+ You can change the table's design without having to change the views associated with it
+ You can restrict the number of rows or columns retumed by the view
+ You can provide simple access to data retrieved from multiple tables through the use of
joins contained in the view
‘To take full advantage of views, you should have a security strategy for your database. That
permits you to attach security permissions to views instead of tables, which makes it easier to
‘grant and revoke permissions from different types of users. We discuss security in the Managing
Users and Security in SQL Enterprise Manager section later in this chapter.
Creating Views in SQL Server Enterprise Manager
As with many of the database objects that you can create in SQL Server, you can create views in
either SQL Query Analyzer or SQL Server Enterprise Manager. Both techniques are fundamen-a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.12
Getting Started with SQL Server 2000
Cuarten 3
Using Views in a Production Application
A view is a construct that gives you greater control over the retrieval of data in your SQL. Server
database. This control manifests itself in various ways. By limiting the number of rows or
columns retrieved by the view, you control the data that a particular user can retrieve. This con-
trol can enable you to do neat tricks, such as create selection criteria that are known only to you
or lock out users from particular subsets of your data based on their security permissions. You
can do these things because each object in the database—including tables, views, and stored
procedures—can be associated with individual users or security groups. In a database that takes
advantage of views and stored procedures, direct access to tables is generally limited to the
database administrator; client applications are limited to accessing views or stored procedures
that, in turn, are responsible for retrieving data from base tables.
A Hide column is an example of an application of this technique. If the Hide column of a record
is set to True, that row is never returned to a user; it’s filtered out by the view responsible for
retrieving the data from the database. Client applications never know that anything has changed
because they're always issuing requests to the same view,
Accessing databases through views, rather than through direct access to tables, is an important
component of any robust production SQL Server database installation. In addition to enabling
you to limit the number of rows and columns retrieved, shielding your database tables with
views gives you the capability to change things without breaking client applications.
‘This process of inoculating your database design from modifications caused by changes in busi-
ness rules can be taken a step further by introducing middle-tier components. Conceptually, such
‘components are similar to views and stored procedures in that they shield your database design
from changes in your software application's mission, but they have advantages over views and
procedures stored in SQL Server. Among these advantages are the fact that they're easier to
program, they return data in the form of objects instead of rows and columns, and they aren't
tied to any one database management system or programming language. (See Chapter 12 for
more about middle-tier components.)
Creating Views with an SQL Query Analyzer Batch
You can create views with SQL Query Analyzer. The process for doing so is less graphical but
more flexible than creating views in Enterprise Manager. To create a view of tblEmployee that
doesn't contain the (confidential) Salary field, using SQL Query Analyzer, follow these steps.
1. Enter the following code in the Query Analyzer query window. (This batch is written in
such a Way that it will create the view whether or not it currently exists.)
USE novelty
60
DROP VIEW Employee_view
coa
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.a
You have either reached 2 page thts unevalale fer vowing or reached your ievina tit for his
book.116
| Geting Stared with SQLServer 2000
CHarter 3
‘SQL Query Analyzer toolbar. The procedure executes and (if there is any data in the table)
returns a result set in the Grids (or Results) tab.
4, Select the Stored Procedures node in the Enterprise Manager’s SQL Servers console win-
dow to verify that the newly stored procedure has been created (you may need to click on
the Refresh button on the toolbar to force the Servers console window to be updated).
Of course, you can run a stored procedure by directly running the SQL Query Analyzer—you
don’t need to start it from within the SOL Server Enterprise Manager.
Creating Stored Procedures in SQL Query Analyzer
‘The steps for creating stored procedures in SQL Query Analyzer are nearly identical to the way
you create them in SQL Enterprise Manager.
Note
Be sure that you create the stored procedure in the Novelty database. It’s easy to for-
get to switch to the correct database (using the USE command or listbox in SQL Query
Analyzer) before issuing commands against it. Creating stored procedures with SQL
Server Enterprise Manager makes committing this error harder.
To create a stored procedure in SQL Query Analyzer, execute the Create Procedure command.
1. In SQL Query Analyzer, enter the following code in the Query window:
CREATE PROCEDURE GetCustomerFromID
@custID int
as
SELECT * from tblCustomer
WHERE ID = @custID
2. This code creates a stored procedure called GetCustomerFromI0. It takes a parameter,
@custID, and returns a record for the customer that matches the @custID argument. (Be-
cause the ID field is tblCustomer's primary key, this procedure will always return either
zero or one record.)
3. Execute the command to create the stored procedure.
4. Return to the Query window and test your stored procedure by running it. To run it, try to
retrieve a record from the table by typing the code
GetCustomerFromID 22