1. Trang chủ
  2. » Công Nghệ Thông Tin

Tài liệu MASTERING SQL SERVER 2000- P2 ppt

50 320 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Tiêu đề Introduction to SQL Server 2000
Trường học University of Information Technology
Chuyên ngành Computer Science
Thể loại Giáo trình
Năm xuất bản 2000
Thành phố Hanoi
Định dạng
Số trang 50
Dung lượng 1,56 MB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

First on the list is Query Analyzer, a tool that ships with SQL Server.However, we also want to highlight Microsoft Access 2000, part of the Office 2000suite of products, for its easy co

Trang 1

CHAPTER 1 • INTRODUCTION TO SQL SERVER 2000

20

There are a few things to note about this code that will give you a sense of the ibility of the ADO Recordset object:

flex-• Setting the CursorLocation property of the recordset to adUseClient tells ADO

to cache the records locally after they’re retrieved This allows more efficientprocessing and enables some advanced ADO methods

• You can specify that you want a static recordset (one that doesn’t reflect changesfrom other users) as well as the type of locking (in this case, optimistic locking)

to use when you open the recordset

• A recordset is a collection of fields, each with a name and value

• The recordset supports a number of properties, including an EOF property that’strue at the end of the recordset, and a number of methods, including aMoveNext method that moves the cursor to the next record

• To be neat, you can close your ADO objects and set them equal to Nothing toexplicitly free the memory they’re consuming

Figure 1.11 shows the results of running this procedure

‘ Open a connectioncnn.Open “Provider=SQLOLEDB.1; “ & _

“Data Source = (local);” & _

Trang 2

“Initial Catalog = Northwind”

‘ Open a recordset on a tablerst.CursorLocation = adUseClientrst.Open “Shippers”, cnn, adOpenStatic, _adLockOptimistic

‘ Add a recordrst.AddNewrst.Fields(“CompanyName”) = “New Shipper”

End SubYou can see the recordset methods in action here:

• The AddNew method prepares a new row to be added to the recordset

• The Update method saves a new row or changes to data in an existing row

• The Delete method deletes the current row

NOTE In this case, you’re assured that the new row will be the last row in the recordsetbecause the recordset is based on a table that includes an Identity field The server auto-matically assigns ID numbers in increasing order to this field You’ll learn about Identityfields in Chapter 11

Trang 3

CHAPTER 1 • INTRODUCTION TO SQL SERVER 2000

22

Displaying Data on a Web Page

These days, the Internet is everywhere—and where there’s no Internet, there are porate intranets It’s probably inevitable that any developer today will be asked tomake data available via a Web page

cor-There are many ways to do this, of course You can run client-side VBScript codethat connects to a remote server You can create ASP pages that use ADO objectsdirectly on a server to create raw HTML to send to clients You can also write queriesthat directly return XML, which some browsers can display For now, let’s look at thesimplest possible case: using the tools that SQL Server supplies to publish data directly

to a Web page

From Enterprise Manager, you can choose Tools ➣ Wizards and launch the WebAssistant Wizard (How can something be both an assistant and a Wizard? We don’tknow; we didn’t name it.) This Wizard creates a set of SQL Server tasks that create andupdate a Web page based on the data you choose

Using the Wizard is a simple process:

1 Choose the database that holds the data that you wish to publish

2 Assign a name to the Web page and choose a table, SQL statement, or storedprocedure to supply the data

3 Select the columns from your data that you wish to publish

4 Decide which rows to publish

5 Select an update frequency As Figure 1.12 shows, this step is very flexible

6 Choose a filename for the Web page

7 Supply information on formatting your Web page

8 Select a list of hyperlinks for the page to include

9 Decide whether to return all the data or chunks of data

When you’re finished making choices, click Finish—the Wizard does the rest ure 1.13 shows a Web page generated by the Web Assistant Wizard

Trang 5

CHAPTER 1 • INTRODUCTION TO SQL SERVER 2000

24

NOTE You’ll learn more about using SQL Server data with the Internet in Chapters 21and 22

Tour for Users

Some of you aren’t DBAs or developers, just users of data stored in SQL Server bases That’s OK—there’s plenty in the product (and in this book) for you too Infact, we suspect that, increasingly, more people are going to be combinationDBA/developer/users in the future, now that Microsoft has released a desktop version

data-of SQL Server that runs under Windows 95 or Windows 98 In addition to the top version, which includes the management tools, there’s also the Microsoft Data-base Engine (MSDE), which is SQL Server without any of the user interface MSDE isshipped with other Microsoft products such as Microsoft Office or Microsoft VisualStudio

desk-So, in this section, we’ll examine the available tools to use when you just want toget to your data First on the list is Query Analyzer, a tool that ships with SQL Server.However, we also want to highlight Microsoft Access 2000, part of the Office 2000suite of products, for its easy connectivity to SQL Server data

Opening Query Analyzer

For ad hoc queries (that is, queries that haven’t been saved to a database), the tool thatships with SQL Server 2000 is Query Analyzer You can launch this tool by choosingPrograms ➣ Microsoft SQL Server ➣ Query Analyzer from the Start menu You can useSQL Server setup to install Query Analyzer on a computer that doesn’t have SQL Serveritself installed, so that Query Analyzer can be used from anywhere on the network.When you launch Query Analyzer, you’ll be prompted to enter the name of a SQLServer and your authentication information After that, the program will open with ablank query window Figure 1.14 shows the basic Query Analyzer interface In thiscase, one query was executed, and a new window was opened to execute a secondquery The Object Browser, to the right of the Query Analyzer workspace, provideseasy access to the names of all your SQL Server objects As you can see, Query Ana-lyzer can display multiple results at any time

Trang 6

FIGURE 1.14

Query Analyzer

Query Analyzer can show you the results of any Transact-SQL statement SQL, or T-SQL, is the language of SQL Server) For example, you might try executingthis statement in the Northwind sample database:

(Transact-SELECT CompanyName, CountryFROM Customers

WHERE CustomerID > ‘MMMMM’

ORDER BY CountryEven if you don’t know SQL, you can probably guess what this statement does Itreturns the CompanyName and Country fields from the Customers table for all cus-tomers whose CustomerID is greater than (that is, later in the alphabet than)

“MMMMM” The results are sorted by the customer’s country Although SQL is a cialized language, by and large, you can read SQL as plain English and get the idea

spe-NOTE You’ll learn a lot more about SQL in Chapters 5 through 8 Appendix A contains

a summary of important Transact-SQL statements

Trang 7

CHAPTER 1 • INTRODUCTION TO SQL SERVER 2000

26

Other Query Analyzer Features

Query Analyzer is a pretty flexible tool Some of the other actions you can do fromthis interface include:

• Saving queries to text files and reloading them later

• Viewing results in either a grid or plain text

• Checking the syntax of a query without executing it

• Analyzing the indexes in a database to determine whether a particular querywould be helped by additional indexes

• Showing the execution plan for a queryThe last point—showing the execution plan for a query—is worth discussing The

execution plan for a query is the set of steps that SQL Server will follow to get you the

information for which you’ve asked For example, in the SELECT query in the ous section, SQL Server will first find all the rows desired using the index on the Cus-tomerID field and then sort them in the desired order For more complex queries, anexecution plan might have dozens of steps

previ-If you get really familiar with SQL, you can sometimes use optimizer hints in yourqueries to change the execution plan and make it faster for your particular data

WARN I NG Don’t change the execution plan if you don’t know what you’re doing.SQL Server 2000 does a good job of optimizing queries all by itself

Connecting Access 2000 to SQL Server

Although Query Analyzer is a useful tool, it’s not all that user-friendly You need tounderstand SQL to do much of anything with Query Analyzer Wouldn’t it be nice tojust view your SQL Server data through a more friendly interface? Well, if you’refamiliar with Microsoft Access and you have Access 2000, you can do just that.Access 2000 includes a new type of database called an Access project An Accessproject includes all of the familiar Access user-interface tools such as forms andreports However, instead of storing its data in a Jet database, it stores its data in aMicrosoft SQL Server database In fact, Access 2000 even comes with a desktop ver-sion of SQL Server, the Microsoft Database Engine (MSDE)

Trang 8

You can also create an Access project that shows data from an existing SQL Serverdatabase To do so, follow these steps:

1 Launch Access 2000

2 Choose Create a New Database Using Access Database Wizards, Pages and jects from the opening dialog box

Pro-3 Choose the General tab in the New dialog box

4 Choose the icon for Project (Existing Database) and click OK

5 Assign a name to your project and click Create

6 Enter your SQL Server name, authentication information, and database name inthe Data Link Properties dialog box, and click OK

That’s all there is to it As Figure 1.15 shows, the result of following these stepswith the sample Northwind database is the creation of an Access project showingyour SQL Server data In the figure, we’ve opened up one of the SQL Server tables toshow the data

FIGURE 1.15

An Access 2000 project

Trang 9

CHAPTER 1 • INTRODUCTION TO SQL SERVER 2000

28

Editing Data in Access 2000

Once you’ve created an Access project tied to your SQL Server database, all of theAccess 2000 tools are available to use For example, suppose you want to view andedit your Customer data in a friendly format It’s easy to do using the Access FormWizard:

1 Select a table in the Database Window (for example, Customers)

2 Select Insert ➣ Form from the Access menus

3 Choose Autoform (Columnar) and click OK

The result will be a form similar to the one shown in Figure 1.16

FIGURE 1.16

SQL Server data in an

Access form

From this form, you can perform all of the basic data operations:

• Entering new customers

• Editing existing customers

• Deleting customers that you no longer need

WARN I NG You’re still limited by the way your SQL Server is set up In particular, ifyour DBA has used SQL Server security to prevent you from modifying data, you won’t beable to do so through an Access project However, if you’re your own DBA, working on asingle-user version of SQL Server, this shouldn’t be a problem

Trang 10

Similarly, you can use the Access report Wizards to create summaries and lists ofyour SQL Server data in a format that’s easy to print When you create user-interfaceobjects such as reports in an Access project, the user-interface objects themselves arestored in the ADP file created by Access All of the data objects, such as views ortables, remain on the server.

NOTE For much more information about Access projects, see Access 2000 Developer’s

Handbook, Volume 2: Enterprise Edition(by Paul Litwin, Ken Getz, and Mike Gilbert, ISBN

0-7821-2372-4, Sybex 2000)

Summary

SQL Server isn’t everything to everybody, but in the current release, it certainly hassomething for almost every computer user The range of SQL Server goes from simple

customer databases intended for a single user all the way to terabytes (a terabyte is one

trillion characters) of data in cases such as Microsoft’s TerraServer (http://www.terraserver.microsoft.com) In the rest of this book, you’ll learn about variousaspects of SQL Server:

• Part 1 will teach you basic SQL Server and database concepts

• Part 2 will teach you Transact-SQL

• Part 3 examines the basic SQL Server objects in more detail

• Part 4 covers administrative tasks

• Part 5 reviews the developer tools that ship with SQL Server

• Part 6 deals with SQL Server data on the Web

• Part 7 introduces some advanced concepts

Ready to start? Good! The next chapter will teach you basic database concepts

Trang 12

CHAPTER 2

Overview of Database Concepts

Application Programming Interfaces 58

Trang 13

Before we get started with Microsoft SQL Server, we want to step back for a

few moments and discuss the basic ideas of database technology Depending

on your experience, you might already know everything in this chapter, inwhich case you can just skim it to make sure the terminology we use is theterminology with which you’re familiar On the other hand, if you’ve never workedwith a database before, this will be your introduction to the basic concepts of the field.What’s stored in a database, anyhow? What can you do with a database? We’ll try toanswer those questions here in a very broad fashion You might want to read this chap-ter now to get an overview, and then refer back to it as necessary to refresh your mem-ory on the big picture when you read about the details later in the book

All of the concepts in this chapter will be discussed later in the book in the context

of SQL Server For example, one of the first things we’ll introduce in this chapter isthe notion of a database table All of Chapter 11 is devoted to tables as implemented

by SQL Server So while you read the current chapter, if you want to know themechanics of working with a particular piece of your database, you can follow the ref-erences forward to the specific chapters For now, we’ll start with a general overview

Databases

A database is a place to store data Suppose you’re running a small business and you

want to store all of the data that pertains to that business Your data is not just a bigheap of disparate facts (or at least, it shouldn’t be a big heap if you want to be able tofind things) The facts are naturally organized into a hierarchy

For example, consider a single fact: A particular employee of your company washired on October 17, 1993 By placing that fact together with other facts, you canorganize your database at four levels:

• The hire date of the employee

• All of the important facts about that employee

• All of the important facts about all employees

• All of the important facts about your entire business

In database terms, you refer to these four levels of organization by four specialterms:

• The field holds an individual fact.

• The record holds all facts about an entity.

• The table holds all facts about a group of similar entities.

• The database holds all facts about all the entities in a connected whole.

Trang 14

Strictly speaking, if a database allows for storing records, fields, and tables, that’sall it really needs to keep track of Some simple databases go no further than this.

However, many database manufacturers add storage for additional things to theirdatabase Microsoft SQL Server in particular stores many things in the database otherthan data As you read through this chapter, you’ll encounter these other things

(such as views or stored procedures), which are collectively called database objects.

But first, you should know more about types of databases Specifically, there arethree topics you’ll frequently run across in the database world:

• File-server versus client-server databases

• Relational databases

• OLTP versus OLAP databases

NOTE For more information on the mechanics of creating and managing SQL Server

databases, refer to Chapter 10

File-Server and Client-Server Databases

One important distinction is that between file-server and client-server databases These

two terms refer to fundamentally different ways of working with data

In a file-server database, the data is stored in a file, and individual users of the datatake what they need directly from the file When there is a change to be made, theapplication opens the file and writes new data When existing data is needed for dis-play, the application opens the file and reads the data If there are 20 different usersfor a database, all 20 users are reading from and writing to the same file

In a client-server database, by contrast, the data is still stored in a file, but all access

to the file is controlled by a single master program (the server) When an application wants to make use of existing data, this application (the client) sends a request to the

server The server finds the proper data and sends it back When an application wants

to write new data to the database, it sends the data to the server, which does theactual writing Only a single program reads and writes from the data files

Typically, databases aimed at a single-user desktop (such as Microsoft Access orMicrosoft FoxPro) are file-server databases Databases that are aimed at departmental,company, or enterprise users (such as Oracle, Informix, or Microsoft SQL Server) areclient-server databases Client-server databases have several important advantages inlarge-scale use These include:

• Because only a single program is reading and writing data, there is less chance ofaccidental changes or crashes destroying vital data

Trang 15

CHAPTER 2 • OVERVIEW OF DATABASE CONCEPTS

• Because all the reading and writing is being done by a single computer, it’s easier

to increase database performance by upgrading that one computer

• Client-server databases also tend to offer features that protect your data, such aslogging transactions and recovery from disk or network errors Strictly speaking,these features could be offered by file-server databases as well, but in practice,they’re found only in the more expensive client-server market

Relational Databases

A relational database is one that stores your data in multiple places called tables, while

also keeping track of how those tables are related to one another Sometimes you’ll

see the term RDBMS, which stands for Relational Database Management System, used

for a relational database

For example, consider a database that’s used to keep track of students in a college.You might want to collect information about students, courses, and instructors Each

of these would be stored as a single table, which would have names:

NOTE SQL Server is a relational database

OLTP and OLAP Databases

Another important distinction is that between online transaction processing (OLTP) and online analytical processing (OLAP) databases The distinction is not as clear-cut as that

between file-server and client-server In fact, most databases will be used as both OLTPand OLAP products during their lifetime

Trang 16

OLTP refers to a usage pattern involving rapid insertion, deletion, and updating ofdata This is typical of many applications For example, suppose you’re running atravel agency and have 20 agents all updating a database of customer trip informa-tion This would be a typical OLTP application The ability to quickly locate andchange data is of paramount importance to avoid the database becoming a bottleneckfor the entire operation.

On the other hand, suppose you’re the manager of the travel agency You might beinterested in seeing summary information from many bookings Perhaps there’s a pat-tern where women travel more to Greece and men more to Spain; knowing this couldenable you to better target your advertising to appropriate periodicals Such analysis,involving summaries of all or most of the data in a database, is the hallmark of OLAPapplications

It’s very difficult for a server to be efficient for both OLTP and OLAP applications

The data structures that are appropriate for fast updating are suboptimal for aggregatequerying Microsoft solves this problem by shipping two servers together The first,Microsoft SQL Server 2000, is mainly an OLTP server It can perform summary queries,but it’s not optimized for them That’s the job of the second program, Microsoft SQLServer 2000 Analysis Services This second program ships with every copy of SQL Server and is designed to build efficient structures for OLAP applications to use

NOTE You’ll learn more about Microsoft SQL Server 2000 Analysis Services in Chapter 28

Transaction Logs

Another feature commonly found in client-server databases is the transaction log This

is a separate file (or other distinct storage area) where the database server keeps track

of the operations it is performing For example, suppose you add a new record to atable Before it adds the record to the table, the database server will make an entry inthe transaction log that says, essentially, “About to add this record to the table,” alongwith the data from the record Only after the transaction log entry has been saveddoes the server actually save the change to the database

Transaction logs are an important part of protecting your data By keeping track ofoperations in a log, the database server makes it possible to recover from a wide range

of disasters For example, suppose that the hard drive that stores your database fails Ifyou’ve kept backups, and if the transaction log is stored on a separate hard drive(both worthwhile precautions), you can easily recover the data by first restoring thebackup and then telling the server to reapply all the changes that were noted in thetransaction log after the backup was made

Trang 17

CHAPTER 2 • OVERVIEW OF DATABASE CONCEPTS

FIGURE 2.1

A table about employees

Much of the work you do with a database will revolve around tables There are fourbasic operations that every database supports:

• Adding information to a table

• Updating information that already exists in a table

• Deleting information from a table

• Viewing information contained in a tableGenerally speaking, you’ll perform these operations by executing SQL statements.SQL stands for Structured Query Language, a standard computer language for workingwith the contents of a database You’ll learn more about SQL later in this chapter andthroughout this book

Trang 18

Records, Fields, and Values

Every table is made up of records and fields A record is all of the information about one

of the entities within a table A field is a particular piece of information stored in a

table For example, referring back to Figure 2.1, the first record is all of the informationfor the employee named Nancy Davolio, Employee ID 1 Some of this information islisted in the figure, while the rest is off to the right and not visible On the other hand,there’s also the EmployeeID field, which has the values 1 through 9 for the records inthis particular table

Depending on what you’re doing, it is sometimes convenient to manipulaterecords, and sometimes fields For example, if you want to know everything stored in

a database about a particular employee, you’d retrieve that employee’s record fromthe appropriate table However, if you want to know the dates of birth of all youremployees, you’d need to inspect the contents of the BirthDate field for all records inthe same table

WARN I NG Note the ambiguous nature of the term field.Sometimes it refers to anindividual piece of information; sometimes it refers to every piece of similar information

within a table When the meaning isn’t clear from context, we’ll refer to these as a field in

a record and a field in a table if it’s necessary to differentiate between them.

When you inspect a particular field in a particular record, what you see is the value

of that field in that record For example, the value of the first field in the first record

in this table is the number 1

Rows and Columns

You’ll also find records and fields referred to as table rows and columns It’s easy to see

why this is if you look at Figure 2.1 Database tables are traditionally displayed on agrid, with the fields running across and the records running down So you might refer

to the row in the table for Nancy Davolio, or the column containing information onlast names The terms are completely equivalent, and there’s seldom a reason for pre-ferring one set to the other The SQL Server documentation usually uses row and col-umn, but much general database literature is written in terms of records and fieldsinstead

Trang 19

CHAPTER 2 • OVERVIEW OF DATABASE CONCEPTS

38

Null Values

As we mentioned above, a value is the actual data stored in a particular field of a ticular record But what happens when there is no data? Consider, for example, adatabase that records customer information One of the things that you’d like to keeptrack of is the fax number for each customer However, some customers won’t havefax numbers Or perhaps they have a fax, but you don’t know the number Figure 2.2shows a SQL Server table illustrating this The highlighted customer, Antonio MorenoTaqueria, doesn’t have information stored for their fax number in this database

par-FIGURE 2.2

Customer with no fax

number

As you can see in the figure, the answer to this problem is something displayed as

<NULL> This is SQL Server’s way of displaying a null value A null value represents theabsence of information You can think of it as a placeholder value in a table; it’s thedatabase’s way of telling you that it doesn’t know what data belongs in that field.Because nulls represent missing information, they cause what is sometimes called

null propagation If you use a field with a null value in a calculation, the result will

always be null For example, you might calculate a line item total by multiplyingquantity times unit price If the quantity for a particular record is null, the answer willalso be null If you don’t know how many you’re buying, you can’t know what thetotal cost will be, either

Trang 20

Field Properties

Not all fields are created equal That’s obvious if you stop to think about it for amoment: Phone numbers look different from birth dates, which in turn look differentfrom last names A full-featured database such as SQL Server lets you capture these dif-

ferences by specifying field properties.

Figure 2.3 shows a different way of looking at the Employees table in a SQL Server

database This view shows the schema information for the table, rather than the data

that the table contains The schema of a database is a way of referring to all of thedesign information that constrains what can be stored in that database

Trang 21

CHAPTER 2 • OVERVIEW OF DATABASE CONCEPTS

The column name of a field (or column) provides a way to refer to that field in thetable Generally speaking, you’ll want to assign meaningful names to your fields, aswas done in this example

The datatype for a field constrains the data that can be stored in that field TheLastName field holds data of the type nvarchar That’s a SQL Server datatype thatrefers to Unicode data of varying length, stored as characters Other datatypes includeint (for integers), datetime (for date or time information), and binary (for informationsuch as pictures)

The length property for a field specifies the maximum amount of data that you canstore in that field

The allow nulls property for a field shows whether null values are allowed in thatfield If a field doesn’t allow nulls, you must supply a non-null value for that field ineach record before you can save the record

By using field properties to distinguish one field from another, you help keep yourdatabase neat and orderly That’s one of the things that distinguishes databases fromspreadsheets With a database, you can use field properties to set rules that the data-base automatically enforces, so that the data you store actually makes sense

Keys and Relationships

Looking again at Figure 2.3, you’ll see a little key symbol to the left of the EmployeeID

column That indicates that this column is the primary key for this table A primary key is a piece of unique identifying information that lets you find a particular record

within a table No two records in the same table can have the same value in the mary key field A primary key might be made up of a single field (as in this case) ormultiple fields For example, suppose you have a table of students with fields for firstname and last name There might be many students with the first name of Mary,

Trang 22

pri-the students had unique names, you could choose pri-the combination of first name andlast name as the primary key for this table.

Sometimes you’ll find a good primary key contained within the data of a table Forexample, if you’re tracking craters on the moon, you’ll discover that no two cratershave the same name, in which case you could use the crater name as the primary key

This is called a natural key In other cases, you’ll have to add something to the data to

provide a primary key For example, if you’re creating a database of newspapers, you’ll

find many newspapers named The Post In this case, you could assign each newspaper

an arbitrary number and store that number in a field named NewspaperID This is

called a synthetic key.

In addition to primary keys, there’s another important type of key in database

theory This is the foreign key The purpose of a foreign key is to allow you to match

up records from two or more tables For example, take a look at the Customers andOrders tables in Figure 2.4

Trang 23

CHAPTER 2 • OVERVIEW OF DATABASE CONCEPTS

42

In the Customers table, the primary key is the field named CustomerID, which has

a unique value for each customer In the Orders table, the primary key is the fieldOrderID, which has a unique value for each order However, notice that the Orderstable also contains a field named CustomerID and that the values in this field aredrawn from the Customers table For example, the order that has the value 10259 inthe OrderID field has the value CENTC in the CustomerID field, which is also thevalue in the CustomerID field of one of the records in the Customers table

We say that CustomerID in the Orders table is a foreign key Its purpose is to allowyou to find the customer who placed a particular order In database terms, this isreferred to as a relationship between the two tables; the Orders table and the Cus-tomers table are related through their primary key–foreign key connection

Figure 2.5 shows a database diagram for the Northwind sample database on SQLServer, which is the database that contains the tables we’ve been inspecting so far.This diagram shows all of the tables in the database, the names of the fields they con-tain, and their primary keys (marked with the key symbols) It also shows the rela-tionships between the tables by drawing little pipes between them, with a key at theprimary key end and an infinity symbol at the foreign key end

Trang 24

Indexes and Constraints

Other features of tables can limit the data placed in the table Two of these are indexes and constraints.

An index on a table is conceptually very similar to an index in a book An index

in a book provides a way to locate individual pages quickly An index on a table vides a way to locate individual records quickly With a table index, you choosewhich field or fields to index For example, you could index a table of employees byEmployeeID, which would make locating individual employees once you knew thevalue of the EmployeeID field very fast You could also index the same table by thecombination of FirstName and LastName, to make it easier to locate records whenyou know both the first and the last name of the employee

pro-Indexes can be unique or nonunique A unique index serves to limit the data placed

within the table For example, if you created a unique index on a field named Number, no two records in the table could share the same vendor number; the data-base would not allow you to save a record with a vendor number that duplicates that

Vendor-of an existing record

Indexes can also be clustered or nonclustered This term refers to the physical storage

order of the table If you create a clustered index on the CustomerID field of the tomers table, the records are stored on disk in order of CustomerID This makes creat-ing a list of customers in order of CustomerID faster, but it can make it slower to addrecords to the Customers table, because existing records may need to be shuffledaround to create room

Cus-TI P Although a table can have many indexes, it can have only one clustered index

SQL Server offers another type of index called a full-text index Unlike regular

indexes, which are stored with the table that they index, full-text indexes are stored

in special objects called catalogs Full-text indexes are not updated automatically

Rather, they are updated by running a special indexing job on the server However,full-text indexes offer special types of searching that are less precise than those sup-ported by regular indexes When using a regular index to locate a record, you mustsupply exactly the value that was placed in the index When using a full-text index,you can search in a more natural fashion For example, a full-text index could be used

to search for records where any of the following conditions are true:

• The record contains the word connect.

• The record contains the word connect or any of its forms such as connecting or connects.

Trang 25

CHAPTER 2 • OVERVIEW OF DATABASE CONCEPTS

44

• The record contains both the word connect and the word network in any order.

• The record contains the word connect, but not the word disconnect.

• The record contains the word connect within three words of the word network Constraints are rules that apply to the data in a table For example, you might have

the rule that the unit price of all products must be greater than one dollar when theproducts are entered You could enforce this rule by creating a constraint on the Prod-ucts table:

([UnitPrice] >= 1)Any attempt to add or edit a record that breaks this constraint will be rejected bythe database server

NOTE Constraints are covered in Chapter 11, and Chapter 12 is devoted to indexes

Rules and Defaults

Two other objects that you’ll find associated with tables in some databases are rules

and defaults A rule is an expression that can be evaluated as being either True or False

when applied to the value of a particular field For example, a rule might assert thatthe value of a field is between zero and 100 If this rule were associated with a particu-lar field, you’d be prohibited by the server from entering values outside of that rangeinto that field

A default is a separate object that specifies a single value—for example, zero By

associating the default with a column in a table, you make the default value of thatcolumn in new records added to that table equal to the value of the default

Although SQL Server supports both rules and defaults, it does so only for bility with older versions of the software For new development, rules have beenreplaced by constraints, and defaults have been replaced by the default value property

compati-of fields Because they’re obsolete, we won’t cover rules and defaults in this book

Views

Although all of the data in your database is stored in tables, tables often do not sent that data the way you’d like to see it Consider a database with Customer,Employee, Order, and Order Detail tables, for example Looking at a table can get you

Ngày đăng: 24/12/2013, 02:17

TỪ KHÓA LIÊN QUAN