Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 50 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
50
Dung lượng
1,38 MB
Nội dung
W
e’re going to go out on a limb here and assume that you own stuff—
such as clothes, food, VCRs, tools, etc. Most people keep the stuff they
own in their homes, but where? Do you just randomly throw your
stuff in your house and hope you can find it again later? Of course
not—you store your belongings in containers, such as cabinets or dressers, so that you
can find your belongings when you need them. Now go one step further: Do you
keep all of your stuff in the same container? Imagine the chaos that would ensue if
you kept your tools, food, and clothes in the same cabinet—you would not be able to
find anything when you needed it. These principles hold true with SQL Server.
The stuff you own in SQLServer is things such as tables, views, stored procedures,
and other objects. Much like with your clothes, food, tools, etc., you need containers
to store those objects in—with SQL Server, those containers are databases. Again, go
one step further: Do you want to keep all of your objects in the same database? Defi-
nitely not. Just as when you store all of your personal belongings in the same cabinet,
you would have a terrible time sorting out all of the data if it was all in one database.
That is why you need to have more than one database, each dedicated to a specific
task, such as an accounting database to hold all of the accounting objects and data, or
a sales database for the sales objects and data.
It makes sense, then, that before you start creating objects, such as tables and
views, you must create the database that will contain those objects. That is what this
chapter deals with: creating, configuring, and administrating databases. We’ll start by
reviewing the basics of how a database works.
Database Basics
As with anything, you need to understand the basics before you can jump into the
more advanced topics—this is especially true with databases. As we mentioned in
Chapter 3, a database is a series of files on your hard disk. These files are just space
that has been preallocated on the hard disk for storing other SQLServer objects, such
as tables and views. These files on the hard disk can be one of three types: a primary
data file, a secondary data file, and a transaction log file.
The primary data file (with an .MDF extension) is the first file created for the data-
base. This file can be used to store two types of objects: user and system objects. User
objects are such things as tables, views, stored procedures, and the like that are used to
modify or store information that has been input by a user. System tables contain infor-
mation that SQLServer needs to keep your database functioning, such as table names,
index locations, database user accounts, and information about other system objects.
The system tables must reside in the primary data file, but the user information and
other objects can be moved to secondary data files.
2627ch10.qxt 8/22/00 10:45 AM Page 370
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
371
When you run out of room on the hard disk that contains the primary data file,
you can create a secondary data file (with an .NDF extension) on a separate hard disk.
Once you have created the secondary file, you can use it to store user data, such as
tables, indexes, and views, but not system objects (those reside only in the primary
data file). The third type of file requires a little more explanation than the data files.
The third type of file is the transaction log file, and it functions much like a constant
online backup by storing transactions. A transaction is a group of data modification
commands (for example, INSERT, UPDATE, and DELETE) that is contained in a BEGIN
TRAN…COMMIT block and executed as a unit, meaning that all of the commands in
the transaction are applied to the database, or none of them are. There are two types of
transactions that SQLServer understands: implicit and explicit. An implicit transaction
occurs when you send a data modification command to SQLServer without specifi-
cally encasing it in a BEGIN TRAN…COMMIT block—SQL Server will add the block for
you. An explicit transaction occurs when you specifically type the BEGIN TRAN and
COMMIT statements at the beginning and end of your statement block. A typical
explicit transaction might look as follows:
BEGIN TRAN
INSERT RECORD
DELETE RECORD
COMMIT TRAN
SQL Server sees the INSERT and DELETE commands as a single unit of modifica-
tion—either they both happen or neither happens, or in SQLServer terminology,
they are either rolled forward or rolled back. The DELETE cannot happen without the
INSERT and vice versa. Every command in SQLServer that modifies data is considered
a transaction, each having a BEGIN and COMMIT statement, whether or not you put
them there (if you don’t add the BEGIN and COMMIT, SQLServer will).
You might expect each of these transactions to be written directly to the database
file, but that is not the case. When a user tries to modify a record in a database, SQL
Server locates the data page (pages are discussed in Chapter 3) in the database that
contains the record to be changed. Once located, the page in question is loaded into
memory—specifically, it is loaded into a special area of memory called the data cache,
which SQLServer uses to store data that is to be modified. All of the changes to the
page are now made in memory (or RAM, random access memory), because RAM is
about 100 times faster than hard disk, and speed is of the essence.
NOTE As discussed in Chapter 3, a page is 8KB and is the smallest unit of storage in a
SQL Server database.
DATABASE BASICS
Digging into SQL
Server
PART
III
2627ch10.qxt 8/22/00 10:45 AM Page 371
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 10 • DATABASES
372
Leaving those changed records in RAM is a bad idea, though, because RAM is
considered volatile, which means that all of the contents of RAM are erased every
time the computer loses power. If the machine were to lose power, you would lose
all of the changes in the data cache. So rather than leaving those changes at the
mercy of RAM, SQLServer writes the changes made in the data cache to the transac-
tion log at the same time. Now you have a copy of the data in RAM and on the hard
disk in the transaction log file. If the server were to lose power now, all of the
changes stored in the data cache would be erased, but you could still recover them
from the transaction log. In that sense, the transaction log is like a constant online
backup of the data cache.
So why not just write all of the changes from data cache directly to the database
file? Why put the transaction log in the middle? Imagine what would happen to your
database if your server were to crash right in the middle of writing changes from
memory to the data file if there were no transaction log. The transaction would be
partially written to disk, and the original transaction would be erased from memory
with no hope of recovery. However, because the transaction is written to the transac-
tion log first, if the server crashes, the original transaction is preserved, and partial
transactions are not written to the database.
In fact, if a crash occurs, SQLServer reads the transaction logs for each database
looking for completed transactions that have not been applied to the data file. If SQL
Server finds any, it rolls them forward, writing them to the data file. Any uncom-
pleted transactions (a BEGIN TRAN with no corresponding COMMIT) are rolled back
or deleted from the transaction log. This way, you can recover your databases right up
to the minute of a crash.
Because of the benefits that you gain from transaction logs, they are required for
each database—you cannot have a primary data file without a transaction log. The
transaction log file (with an .LDF extension) should be placed on a separate physical
hard disk than the data file. If the hard disk with the data file crashes, you still have
the transaction log file and the last good backup to re-create the data file on a new
hard disk. The transaction log file should be approximately 10 to 25% of the size of
the data files to accommodate the transactions made during the day. If your users do
not make many modifications to the data, you can go with a smaller transaction log
(10% being the minimum), whereas if your users are constantly modifying the data,
you should make the transaction log file larger (maybe even up to 30%).
NOTE Because all of the changes are written to the transaction log before they are
written to the data file, the transaction log is referred to as a write ahead log.
2627ch10.qxt 8/22/00 10:45 AM Page 372
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
373
Now that you know how these files work, you need to know how big to make
them. Let’s look at capacity planning.
Planning for Capacity
Perhaps you’ve heard the old adage waste not, want not. That rings true regarding
hard-disk space on your SQL Server. Because databases are files that are stored on your
hard disk, you can actually waste hard-disk space if you make them too big. If you
make your database files too small, though, SQLServer will have to expand the data-
base file, or you may need to create a secondary data file to accommodate the extra
data—a process that can slow users down. Neither of these options is very appealing,
so you need to find a happy balance between too big and too small, which is going to
require a little math. Here are the general steps to estimate the size of your database:
1. Calculate the record size of the table in question. You get this by adding the size
of each column in the table.
2. Divide 8092 by the row size from step 1 and round down to the nearest number.
The figure 8092 is the actual amount of data a single data page can hold, and
you round down because a row cannot be split across pages.
3. Divide the number of rows you expect to have by the result from step 2. This
will tell you how many data pages will be used for your table.
4. Multiply the result from step 3 by 8192—the size of a data page in bytes. This
will tell you exactly how many bytes your table will take on the disk.
In Chapter 11, you will learn how to plan a database—deciding what tables to put
in it, what datatypes to use, and how big the fields in the tables should be—so we’ll
forego that discussion here. In this section we’re going to assume that the planning
phase is complete and create a sales database that will contain three tables: one for
customer information, one for product information, and one for order detail informa-
tion. To calculate the size of your new database, let’s apply the following steps to the
customers table to discern how big it will be with 10,000 records:
1. Assuming you have already planned your database, add all of the field sizes in
the customers table together. Here is the table layout (you should get 125 bytes):
custid int (note: this is 4 bytes of storage)
fname varchar(20)
lname varchar(20)
address varchar(50)
PLANNING FOR CAPACITY
Digging into SQL
Server
PART
III
2627ch10.qxt 8/22/00 10:45 AM Page 373
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 10 • DATABASES
374
city varchar(20)
state char(2)
zip char(9)
2. Divide 8092 by 125 and round down to the nearest number to find out how
many of these rows can fit on a single data page. You must round down in every
case because a row cannot span a page. The answer should be 64.
3. Divide 10,000 (the estimated number of rows in the table) by the number of
rows on a page (64) and round up to the nearest number. You round up here
because a partial row will be moved to a whole new page—there is no such
thing as a partial page of storage. The answer should be 157.
4. Multiply 157 (the number of pages required to hold 10,000 records) by 8192
(the size of a page on disk). This should be 1,570,000 bytes.
So, with 10,000 records, the customers table in your sales database would require
approximately 1.5MB of hard-disk space. By repeating these steps for each table in the
database, you can figure out approximately how much space to allocate to the data-
base when you first create it.
With all of the math out of the way, you are ready to start creating a database.
Creating Databases
We discussed earlier that a database is comprised of at least two files: first, the primary
data file (with an .MDF extension) and the transaction log file (with an .LDF exten-
sion). There may also be a need for secondary data files if the hard disk that contains
the primary data file fills up, but we will discuss those later in this chapter.
To get started with the database, you only need to create the primary data file and
transaction log file. There are three different ways to go about it:
• By using the Create Database Wizard
• Graphically with Enterprise Manager
• Via Transact-SQL code
We’ll look at each method here, starting with the Create Database Wizard.
TIP New databases are actually a copy of the Model database, because Model has all of
the system objects necessary for any database to function. This means that if you want any
standard objects in all of your databases (for example, a database user account), if you add
the object to the Model database, the object will automatically exist in all new databases.
2627ch10.qxt 8/22/00 10:45 AM Page 374
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
375
Using the Create Database Wizard
Wizards, if you are not familiar with them, are a series of step-by-step screens that
help you accomplish a task with which you may not be familiar. Although Wizards
are most useful for the novice, they can also be a great help to the seasoned adminis-
trator. Wizards not only provide you with a step-by-step process for accomplishing a
task, they also perform all of the menial work involved, allowing you to focus on the
more advanced tasks that come later. The Create Database Wizard is no exception; we
will use it here to create a simple trial database, just to get the feel of the Wizard:
1. If you are not in Enterprise Manager, open it now by selecting it from the SQL
Server 2000 group in Programs on the Start menu.
2. On the Tools menu, select Wizards.
3. Expand Database and select Create Database Wizard. Click OK to start the
Wizard.
4. The opening screen displays a list of what this Wizard is designed to accom-
plish. Click Next to proceed.
5. On the second screen, you are asked for a name for the database and the loca-
tion of the data and log files. For the name, enter Wizard Test and leave the
defaults for the file locations. Click Next.
CREATING DATABASES
Digging into SQL
Server
PART
III
2627ch10.qxt 8/22/00 10:45 AM Page 375
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 10 • DATABASES
376
6. The third screen prompts you for the size of the data file; enter 5 to make the
file 5MB, then click Next.
7. The next screen gives you the option to have the database file automatically
expand when more space is required for data. Leave the defaults here and click
Next; we’ll discuss file growth shortly.
2627ch10.qxt 8/22/00 10:45 AM Page 376
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
377
8. You are asked for the size of the transaction log file. Remembering that this
should be about 10 to 25% of the size of the data file, you will leave the default
of 1MB and click Next.
9. You are asked if you would like the transaction log to automatically expand.
Click Next to accept the defaults.
CREATING DATABASES
Digging into SQL
Server
PART
III
2627ch10.qxt 8/22/00 10:45 AM Page 377
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 10 • DATABASES
378
10. The final screen gives a list of the options that you have chosen. Verify that
these are what you want and click Finish to create your database.
11. When asked if you would like to create a maintenance plan for the database,
click No. You will learn how to create a maintenance plan in Chapter 17.
2627ch10.qxt 8/22/00 10:45 AM Page 378
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
379
12. To verify that the Wizard Test database exists, expand Databases under your
server and click Wizard Test (if it exists). You should see an information screen
pop up in the contents pane (on the right). You may need to refresh the tree-
view in the left pane by right-clicking your server and selecting Refresh to see
the new database.
Using the Create Database Wizard is probably the simplest way to create a data-
base, but because there are eight screens to deal with, this method takes a little longer
than the next method, using Enterprise Manager.
Creating Databases with Enterprise Manager
The next easiest way to create a database in SQLServer is through Enterprise Manager.
This method does not detail each step of database creation and is therefore considered
to be a slightly more advanced method than using the Wizard. Using Enterprise Man-
ager to create a database is also a little faster than using the Wizard because there are
only three screens with which to deal. To help you get the feel of using Enterprise Man-
ager for creating databases, we will use this next series of steps to create a sales database
that can later be filled with tables, views, and other objects for a sales department:
1. Open Enterprise Manager from the SQLServer 2000 group in Programs on the
Start menu and expand your server; then expand the Databases icon.
CREATING DATABASES
Digging into SQL
Server
PART
III
2627ch10.qxt 8/22/00 10:45 AM Page 379
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
[...]... something new to SQL Server 2000— the listbox at the bottom of the screen labeled Compatibility Level This is designed to force your database to behave like one in an earlier version of SQLServer This is useful for older applications that have not yet been updated to function with SQL Server 2000 You will notice three settings here: 60, 65, and 70 The 60 and 65 settings will cause the SQLServer database... smallest unit of storage in SQLServer is an 8KB page, but when SQLServer writes a page to hard disk, the page is written 512 bytes at a time because hard disks store information in 512-byte sectors If a power failure occurs while SQL is writing a page to disk, you may get only part of that page on disk, which is called a torn page When Torn Page Detection is checked, SQLServer marks each 512-byte... the database statistics Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 8/22/00 10:45 AM Page 383 CREATING DATABASES 383 TI P When you create a new object in SQL Server, you may not see it in the contents (right) pane right away Right-clicking the level just above where your new object should be and selecting Refresh will force SQLServer to reread the system tables and... duplicates) If this option is checked, SQLServer will automatically create statistics for any column that is part of an index If this option is unchecked, you must create your own statistics Again, it is best to leave this turned on until you understand SQLServer well enough to outsmart the query optimizer Auto Update Statistics: Setting this option will instruct SQLServer to automatically update your... (note that you should replace the C:\ with the drive on which you installed SQL Server) : CREATE DATABASE DoomedDB ON PRIMARY (name = DoomedDB, filename = ‘c:\Program Files\Microsoft SQL Server\ data\DoomedDB.mdf’, size = 10MB, maxsize = 15MB, filegrowth = 1MB) LOG ON (name = DoomedLog, filename = ‘c:\Program Files\Microsoft SQL Server\ data\DoomedLog.ldf’, size = 2MB, maxsize = 3MB, filegrowth = 10%) 3... ready to start filling the databases with objects In the next chapter, let’s start by creating tables Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark PA R T Digging into SQLServer III This page intentionally left blank Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark 2627ch11.qxt 8/23/00 10:26 AM Page 405 CHAPTER 11 Tables F E AT U R I N G : Planning... The only time to have this option off is if you have a disk cache with a battery backup that is specially designed for database servers; otherwise leave this option checked Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark PA R T III Digging into SQLServer 2627ch10.qxt 2627ch10.qxt 390 8/22/00 10:45 AM Page 390 CHAPTER 10 • DATABASES Auto Close: When a user connects to a database,... space on your hard disk To verify that this database has been created, open Enterprise Manager and expand your server and then databases Notice DoomedDB in the list of available databases Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark PA R T III Digging into SQLServer 2627ch10.qxt 2627ch10.qxt 386 8/22/00 10:45 AM Page 386 CHAPTER 10 • DATABASES Now that your database is... which they are members Dbcreator is Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark Digging into SQLServer III 2627ch10.qxt 388 8/22/00 10:45 AM Page 388 CHAPTER 10 • DATABASES another special group with privileges inside a database Sysadmin is a special group that has administrative control over every database on the server When this option is checked, only members of... purchase PDF Split-Merge on www.verypdf.com to remove this watermark 8/22/00 10:45 AM Page 397 MODIFYING DATABASES 397 3 On the Transaction Log tab, on the second line of the Transaction Log Files section, type doomed_log2 in the File Name field and notice that the rest of the fields are filled in for you Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark PA R T III Digging into SQL . storage in a
SQL Server database.
DATABASE BASICS
Digging into SQL
Server
PART
III
2627ch10.qxt 8/22/00 10:45 AM Page 371
Please purchase PDF Split-Merge. the SQL Server 2000 group in Programs on the
Start menu and expand your server; then expand the Databases icon.
CREATING DATABASES
Digging into SQL
Server
PART
III
2627ch10.qxt