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

Tài liệu MASTERING SQL SERVER 2000- P9 pdf

50 304 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 đề Creating, Configuring, and Administering Databases in SQL Server
Trường học Unknown
Chuyên ngành Database Management
Thể loại Giáo trình
Năm xuất bản 2000
Thành phố Unknown
Định dạng
Số trang 50
Dung lượng 1,38 MB

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

Nội dung

These files on the hard disk can be one of three types: a primarydata file, a secondary data file, and a transaction log file.. System tables contain infor- mation that SQL Server needs

Trang 1

We’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 theyown in their homes, but where? Do you just randomly throw yourstuff in your house and hope you can find it again later? Of coursenot—you store your belongings in containers, such as cabinets or dressers, so that youcan find your belongings when you need them Now go one step further: Do youkeep all of your stuff in the same container? Imagine the chaos that would ensue ifyou kept your tools, food, and clothes in the same cabinet—you would not be able tofind anything when you needed it These principles hold true with SQL Server.The stuff you own in SQL Server 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, goone 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 specifictask, 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 andviews, you must create the database that will contain those objects That is what thischapter deals with: creating, configuring, and administrating databases We’ll start byreviewing the basics of how a database works

Database Basics

As with anything, you need to understand the basics before you can jump into themore advanced topics—this is especially true with databases As we mentioned inChapter 3, a database is a series of files on your hard disk These files are just spacethat has been preallocated on the hard disk for storing other SQL Server objects, such

as tables and views These files on the hard disk can be one of three types: a primarydata 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 SQL Server 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 andother objects can be moved to secondary data files

Trang 2

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 astables, indexes, and views, but not system objects (those reside only in the primarydata 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 BEGINTRAN…COMMIT block and executed as a unit, meaning that all of the commands inthe transaction are applied to the database, or none of them are There are two types of

transactions that SQL Server understands: implicit and explicit An implicit transaction

occurs when you send a data modification command to SQL Server without cally encasing it in a BEGIN TRAN…COMMIT block—SQL Server will add the block for

specifi-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 typicalexplicit transaction might look as follows:

BEGIN TRANINSERT RECORDDELETE RECORDCOMMIT TRANSQL Server sees the INSERT and DELETE commands as a single unit of modifica-tion—either they both happen or neither happens, or in SQL Server terminology,they are either rolled forward or rolled back The DELETE cannot happen without theINSERT and vice versa Every command in SQL Server that modifies data is considered

a transaction, each having a BEGIN and COMMIT statement, whether or not you putthem there (if you don’t add the BEGIN and COMMIT, SQL Server will)

You might expect each of these transactions to be written directly to the databasefile, but that is not the case When a user tries to modify a record in a database, SQLServer locates the data page (pages are discussed in Chapter 3) in the database thatcontains the record to be changed Once located, the page in question is loaded intomemory—specifically, it is loaded into a special area of memory called the data cache,which SQL Server uses to store data that is to be modified All of the changes to thepage are now made in memory (or RAM, random access memory), because RAM isabout 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

Trang 3

Leaving those changed records in RAM is a bad idea, though, because RAM isconsidered volatile, which means that all of the contents of RAM are erased everytime the computer loses power If the machine were to lose power, you would loseall of the changes in the data cache So rather than leaving those changes at themercy of RAM, SQL Server 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 harddisk in the transaction log file If the server were to lose power now, all of thechanges stored in the data cache would be erased, but you could still recover themfrom the transaction log In that sense, the transaction log is like a constant onlinebackup of the data cache

So why not just write all of the changes from data cache directly to the databasefile? Why put the transaction log in the middle? Imagine what would happen to yourdatabase if your server were to crash right in the middle of writing changes frommemory to the data file if there were no transaction log The transaction would bepartially written to disk, and the original transaction would be erased from memorywith 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 partialtransactions are not written to the database

In fact, if a crash occurs, SQL Server reads the transaction logs for each databaselooking for completed transactions that have not been applied to the data file If SQLServer 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 foreach database—you cannot have a primary data file without a transaction log Thetransaction log file (with an LDF extension) should be placed on a separate physicalhard disk than the data file If the hard disk with the data file crashes, you still havethe transaction log file and the last good backup to re-create the data file on a newhard disk The transaction log file should be approximately 10 to 25% of the size ofthe data files to accommodate the transactions made during the day If your users donot 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 arewritten to the data file, the transaction log is referred to as a write aheadlog

Trang 4

Now that you know how these files work, you need to know how big to makethem 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 yourhard disk, you can actually waste hard-disk space if you make them too big If youmake your database files too small, though, SQL Server will have to expand the data-base file, or you may need to create a secondary data file to accommodate the extradata—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 torequire 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, andyou 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’llforego that discussion here In this section we’re going to assume that the planningphase is complete and create a sales database that will contain three tables: one forcustomer 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 thecustomers 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)

Trang 5

city varchar(20)

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 everycase 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 herebecause a partial row will be moved to a whole new page—there is no suchthing 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 requireapproximately 1.5MB of hard-disk space By repeating these steps for each table in thedatabase, 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 primarydata 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 containsthe 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 andtransaction 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 ofthe system objects necessary for any database to function This means that if you want anystandard objects in all of your databases (for example, a database user account), if you addthe object to the Model database, the object will automatically exist in all new databases

Trang 6

Using the Create Database Wizard

Wizards, if you are not familiar with them, are a series of step-by-step screens thathelp you accomplish a task with which you may not be familiar Although Wizardsare 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 atask, they also perform all of the menial work involved, allowing you to focus on themore advanced tasks that come later The Create Database Wizard is no exception; wewill 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

Trang 7

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 clickNext; we’ll discuss file growth shortly

Trang 8

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

Trang 9

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

Trang 10

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 screenpop 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 seethe new database

Using the Create Database Wizard is probably the simplest way to create a base, but because there are eight screens to deal with, this method takes a little longerthan the next method, using Enterprise Manager

data-Creating Databases with Enterprise Manager

The next easiest way to create a database in SQL Server 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 ager to create a database is also a little faster than using the Wizard because there areonly 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 databasethat can later be filled with tables, views, and other objects for a sales department:

Man-1 Open Enterprise Manager from the SQL Server 2000 group in Programs on the

Trang 11

2 Right-click Databases and select New Database.

3 On the General Tab, enter Sales in the Name box.

4 At the bottom of the General tab, leave Server Default for collation and move to

the Data Files tab The collation setting changes how SQL Server stores ters in your tables

charac-5 Notice that the filename text box has been filled in for you In the Initial Size

field, enter 10.

6 Make certain Automatically Grow File is selected—this will allow the data file to

automatically expand when more space is needed

7 Leave file growth at 10% This means that the data file will grow 10% at a time;

for example, if the file was 100MB, it would grow by 10MB

8 Maximum File Size should be restricted to 15MB, meaning that the data file

will not automatically grow past 15MB If you set it to Unrestricted FileGrowth, the data file could fill the entire hard drive, which could make yourcomputer crash if the data file is on the same hard disk as other programs (such

as the Windows 2000 operating system)

Trang 12

9 Click the Transaction Log tab and notice that the name here is filled out as well.

10 Since the transaction log should be about 10 to 25% of the size of the data files,

you will set the initial size to 2

11 Make sure that Automatically Grow File is selected and leave the growth at 10%.

These settings have the same effect as the growth settings on the data files

12 Set the Maximum File Size to 3MB.

Trang 13

13 Click OK to create the database.

14 To verify that the new database exists, right-click the Databases icon in the left

pane and select Refresh, then notice the Sales database under Databases Thecontents pane should display all of the database statistics

Trang 14

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 SQL Server to reread the system tables and display anynew objects in your database

The sales database is now ready to be filled with other objects (for example, tables

or views), and it didn’t take long to create at all However, imagine how long it wouldtake to create a 700GB database This is a task that you should schedule for off hours,and the only way to schedule database creation is by using the third and final methodfor creating a database: Transact-SQL

Creating Databases with Transact-SQL

Although using Enterprise Manager is an effective and easy way to create a database,there is no way to schedule the creation of the database for a later time using thegraphic method “Why would I want to schedule it?” you ask In the last section, youcreated a small database that took just a few minutes to create, but imagine how long

it would take to create a 700GB database—several hours, to be sure That is not anactivity you would want to engage in during business hours because it would slowyour users down tremendously You can, however, combine your forthcoming knowl-edge of scheduling tasks in SQL Server with the T-SQL (a shortened form of Transact-SQL) code for creating databases to schedule the creation of massive databases duringoff hours The syntax for the CREATE DATABASE statement looks as follows:

CREATE DATABASE database_name

ON [PRIMARY]

(

NAME=logical_file_name, FILENAME=’os_file_name’, SIZE=size (in MB or KB), MAXSIZE=maximum_size (in MB or KB) or UNLIMITED (fill all available space), FILEGROWTH=growth_increment (in MB or KB)

)LOG ON (

NAME=logical_file_name, FILENAME=’os_file_name’, SIZE=size (in MB or KB),

Trang 15

FILEGROWTH=growth_increment (in MB or KB)

)[ FOR LOAD | FOR ATTACH ]Here’s an explanation for each of the items in the above listing:

database_name: This is the name of the new database and can be up to

NAME: This option specifies the logical name of the database, which will beused to reference the database in Transact-SQL code This option is not requiredwhen FOR ATTACH is used

FILENAME: This is the name and path of the database file as it is stored onthe hard disk This must be a local directory (not over the network) and cannot

be compressed

SIZE: This is the initial size of the data files It can be specified in MB or KB

If you do not provide a size for a primary data file, SQL Server will generate afile that is the same size as the Model system database If a size is not providedfor a secondary file, SQL Server automatically makes it 1MB

MAXSIZE: This is the maximum size that the database is allowed to reachautomatically This can also be in MB or KB, or UNLIMITED can be specified,thus instructing SQL Server to expand the data file to fill the entire hard disk

FILEGROWTH: This is the increment in which to expand the file It is ified in either MB, KB, or percent (%) If none of these symbols are used, MB isassumed

spec-LOG ON: This specifies where the log files are to be created and their size IfLOG ON is not specified, SQL Server will create a log file that is 25% of the size

of all data files, and that has a system generated name and is placed in thesame directory as the data files It is best to use LOG ON to place the transac-tion log file on a separate physical hard disk from the data files so that, in theevent of a system crash, you will be able to access all of the transactions thatoccurred before the disaster

FOR LOAD: This option is for backward compatibility only It was used inrestore processes to re-create a database without initializing it on disk (initializ-

Trang 16

ing was the process of preparing the database file to accept data) This is nolonger needed since the SQL Server restore process now re-creates databases inthis fashion by default

FOR ATTACH: This is used to attach a set of database files that were created

on a different server or have been detached from the current system Attaching

is the process of adding a new record in the sysdatabases table on the Masterdatabase to inform SQL Server where each file is and how it is to be used Thisshould be used when 16 or more data files need to be attached to the currentserver For less than 16 data files, use the sp_attach_db stored procedure

Use the following steps to create a database with T-SQL code (we’ll use this to testdropping databases later in this chapter):

1 Open Query Analyzer and log in using Windows NT Authentication

2 To create a 10MB database named DoomedDB on the C drive with a 2MB log

file, execute the following code (note that you should replace the C:\ with thedrive 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 In the results pane (on the bottom) in Query Analyzer, you should see two

mes-sages stating that the data and log files have been allocated space on your harddisk To verify that this database has been created, open Enterprise Manager andexpand your server and then databases Notice DoomedDB in the list of avail-able databases

Trang 17

Now that your database is created, there are a few configuration changes that youcan make to modify the way your database works.

Modifying Databases

As noted earlier, new databases are copies of the Model database This means that allnew databases have a standard set of options that control their behavior Theseoptions may need to be changed according to the function of the database

Not only do you need to change the options that control the database, you mayneed to change the size of the database as well, expanding it or shrinking it If youexpand the database, you may need to expand it to another physical hard disk, whichmeans adding secondary data files or transaction log files to the database These sec-ondary files may need to be added to filegroups so that you have better control overobject placement

In this section we are going to discuss what may be necessary to make your bases behave the way you need them to, how to change the size of the database, andhow to add files and filegroups

Trang 18

data-Setting Database Options

If you have ever bought a new car or at least watched commercials for new cars, youknow that cars come with options Options on a car include the radio and anti-lockbrakes—things that would not ordinarily come with a floor-model car Such optionsmake the car behave differently SQL Server databases also have options that you canset to make the database behave differently So before you jump in and start usingyour database, you may want to consider setting some of those options

Most of these database options can be set using Enterprise Manager If you click one of your databases, select Properties, and then select the Options tab, you willsee what is shown in Figure 10.1

right-FIGURE 10.1

The Options tab

Here is a list of what those options are for and when you should use each one:

Restrict Access: This option will allow you to control which users canaccess a database There are two options:

Members of db_owner, dbcreator, or sysadmin: There is a specialgroup in each database called db_owner whose members have administra-tive control over the database of which they are members Dbcreator is Digg

Trang 19

another special group with privileges inside a database Sysadmin is a specialgroup that has administrative control over every database on the server.When this option is checked, only members of these three groups can accessthe database People already using the database won’t be disconnected, but

as soon as they exit, they can’t come back in Use this option during initialdatabase development or when you need to change the structure of one ofthe objects in the database, such as adding a column to a table

Single User: When checked, this option changes the database to allowonly one user at a time to connect That one user could be anybody, butsince you are the one setting the option, it should be you You should setthis option just before restoring or renaming a database since you don’twant anyone, including other members in the db_owner role, trying to usethe database during these activities

Read-Only: Exactly like it sounds, this option makes a database read-only—

no writing can occur There are a few notable side effects to this option First,read-only databases are skipped during autorecovery, a process at systemstartup that verifies that all committed transactions have been written to alldatabases Second, SQL Server places locks on data that is being read in a stan-dard database so that users do not try to modify data that is being read by otherusers However, since no writing can occur on a read-only database, no locksare placed on the data, which can accelerate data access Because of this, read-only is a good option to set on databases that do not change often, such as anarchive database or a decision-support database

ANSI NULL Default: When you create a table in SQL Server, you can ify whether the columns in the table can be empty—a condition referred to asnull If you do not specify nullability on your columns when you create ormodify a table, and if this option is not checked, your column will not allownull values If this option is checked and you do not specify nullability on yourcolumns when you create or modify a table, they will accept null values Thisoption is a matter of personal preference; if most of your columns should notcontain null values, you should leave this option off—the default setting

spec-Recursive Triggers: Triggers are watchdogs for your tables They can bedefined to fire (activate) whenever someone inserts, updates, or deletes data, tomake certain that your complex business logic is applied For example, if youhave a database that has one table with managers and another with employees,you could create a DELETE trigger on the managers table that would ensurethat you are not trying to delete a manager with employees underneath themwithout first assigning another manager to the employees When checked, this

Trang 20

option will allow triggers to fire other triggers For example, a user could update

an orders table, which fires a trigger on a customers table The trigger from thecustomers table could update the orders table If this option is set to True, theoriginal trigger (on the orders table) would fire again; if this option is set toFalse, the original trigger would not fire again This option is for very complexlogic and should be used only when you fully understand all of your triggersand tables

Select Into/Bulk Copy: Earlier you learned that all transactions that makemodifications to a database are written to the transaction log before they arewritten to the database Imagine, though, if you were trying to import 500MB

of text into a 500MB database Since the transaction log is only about 25% ofthe size of the database, you would be pumping all that data through a 125MBlog The log would therefore act as a bottleneck and slow the process to a crawl

Checking this option instructs SQL Server to bypass the transaction log andwrite all modifications directly to the database You should use this option onlywhen you are doing massive data imports If you find that you need to use thisoption, you must back up your database immediately afterward since it is in avulnerable state and turn this option off as soon as you are finished

Truncate Log on Checkpoint: Normally your transaction log retains all ofthe transactions written to it until you perform a transaction log backup; thenall of the old transactions are purged from the log To test your database afteryou first create it, you will probably fill it with junk data Because you don’tcare about recovering the test data, you can check this option to clear the trans-action log completely every time the data is written to the database file When

your database is complete and being used on a regular basis (referred to as in

production), you should uncheck this option If you leave this option on, you

will lose the up-to-the-minute recoverability afforded by the transaction log

Torn Page Detection: The smallest unit of storage in SQL Server is an 8KBpage, but when SQL Server writes a page to hard disk, the page is written 512bytes at a time because hard disks store information in 512-byte sectors If apower 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 ischecked, SQL Server marks each 512-byte sector of a page with a special bit; ifthat bit is in the wrong state when the page is read during the autorecoveryprocess, the page is considered torn and should be removed The only time tohave this option off is if you have a disk cache with a battery backup that isspecially designed for database servers; otherwise leave this option checked

Trang 21

Auto Close: When a user connects to a database, it must be opened When adatabase is open, it consumes system resources such as RAM and CPU time.When this option is checked, it will close the database when the last user dis-connects from it Because there is not usually an abundance of availableresources on a desktop system, the default for this option in the Desktop Edi-tion is set to on That way a database will be closed when not in use On allother versions, this option is unchecked because users would be opening andclosing the database all day and night, and that would slow down your system.

Auto Shrink: SQL Server periodically scans your databases to see whetherthey contain more than 25% free space; if so, SQL Server can automaticallyreduce the size of your database so that it contains only 25% free space If thisoption is checked (the default in the Desktop Edition), autoshrink can occur; ifthis option is unchecked (the default in all other editions), autoshrink does notoccur It is best to leave this option set to the default since the autoshrinkprocess can consume system resources on a server, and you don’t want to wastedisk space on a desktop We’ll discuss how to manually shrink databases on aserver shortly

Auto Create Statistics: When you send a query to the database server, thequery is intercepted by the query optimizer, whose sole purpose is to find thefastest way to return a result set It does this by reading statistics about each

of the columns mentioned in your SELECT statement (these statistics are based

on the number of values in the column you are selecting from that are uniqueand the number of duplicates) If this option is checked, SQL Server will auto-matically 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 thisturned on until you understand SQL Server well enough to outsmart the queryoptimizer

Auto Update Statistics: Setting this option will instruct SQL Server toautomatically update your statistics from time to time If this is off, you mustupdate the statistics manually Uncheck this option if you are low on systemresources (such as RAM or CPU time) You can create a database maintenanceplan that will accomplish this task on a scheduled basis later

Use Quoted Identifiers: If you are going to use spaces in a table name

(such as Order Details in the Northwind database) or reserved keywords (such as

check or public), you would ordinarily need to encase them in square brackets

([ ]) If this option is checked, you can use double quotation marks (“”) as well.There are more database options that do not show up on the Options tab To setthose options, you must use the sp_dboption stored procedure It looks as follows:

Trang 22

Here is a list of the remaining options with which you have to work:

ANSI Nulls: When this option is checked, any comparison made with a nullvalue will yield an answer of null If this option is unchecked, comparisons ofnon-Unicode data with null values yield False, and null-to-null comparisonsyield True This option is unchecked by default

ANSI Warnings: You know that it is not possible to divide anything byzero, but the computer has to be told If this option is unchecked and you try

to divide by zero or use a null value in a mathematical equation, your answerwill be null, and you will see no error If this option is checked, you will receive

a warning This option is unchecked by default

Concat Null Yields Null: String concatenation combines multiple strings

into one string by using a + operator For example, Hello my name + is Joe would return Hello my name is Joe as one string If this option is checked and you try to concatenate Hello my name + null, you would get null If this option is

unchecked and you try to concatenate Hello my name + null, you would get

Hello my name This option is unchecked by default.

Cursor Close on Commit: A cursor can be thought of as a subset of a resultset Cursors return single rows of data at a time and therefore make dataretrieval faster in the case of a large result set If you check this option, cursorsare closed as soon as transactions are committed It is better to leave this optionunchecked so that cursors stay open until all data modifications are complete

The cursor can then be closed manually

Default to Local Cursor: When this option is checked, any cursor created

is local to the procedure that called it, which means that if you execute a storedprocedure (a prewritten query stored on the SQL Server) that creates a cursor,only that stored procedure can use that cursor If this option is unchecked (thedefault), any other procedure used by the same connection can use the cursorthat was created Therefore, if Joe executes a stored procedure that creates a cur-sor, any other procedure that Joe executes can use that cursor when this option

is unchecked If this option is checked, only the stored procedure that createdthe cursor could reference it

Merge Publish: Replication is used to copy a database to multiple serversand keep those copies constantly updated One type of replication is mergereplication, in which users can make changes to all copies of the database onany server and have those changes replicated to every other copy This option

is set during the configuration of replication, so you will not actually use it

However, when it is checked, the database can be merge replicated

Trang 23

Offline: This option is used to take a database offline, making it inaccessible, sothat it can be duplicated on some type of removable media (such as a CD-ROM)

Published: You won’t set this option—it is set when you enable a database

to be published via replication Publishing a database means that it can be

copied to other servers, called subscribers.

Subscribed: You won’t set this one either—it is set when you enable a base to subscribe to a published database via replication

data-NOTE A few of these options deal with Unicode data, which stores characters using 2bytes (or 16 bits) instead of the standard single byte (8 bits) This allows you to store65,536 different characters in Unicode as opposed to the 256 characters that you get withthe standard ANSI character set

Besides these options, you probably noticed 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 SQL Server This isuseful for older applications that have not yet been updated to function with SQLServer 2000 You will notice three settings here: 60, 65, and 70 The 60 and 65 settingswill cause the SQL Server database to behave just as it would in SQL Server 6 or 6.5.The 70 setting forces complete compliance with SQL Server 7 Some examples of thiswould be as follows:

• In 60 or 65 compatibility mode, a SELECT statement that has a GROUP BYclause but no ORDER BY clause will be sorted by the columns listed in theGROUP BY clause In 70 compatibility mode, no sorting takes place without theORDER BY clause

• In 60/65 mode, table aliases can be used in the SET clause of an UPDATE ment The 70 mode does not allow table aliases in UPDATE statements—youmust use the table name specified immediately after the UPDATE statement

state-• In 60/65 mode, when creating or altering a table with a bit datatype column, ifyou do not specify nullability of the column, it is set to NOT NULL (meaningthat it will not accept null values) In 70 mode, the nullability of bit columns isset by the current session setting

• In 60/65 mode, you cannot use the ALTER COLUMN clause on ALTER TABLE In

70 mode, this is perfectly acceptable

Trang 24

• In 60/65 mode, if a trigger is without the WITH APPEND option, any existingtrigger of the same type will be overwritten In 70 mode, the WITH APPENDoption is assumed so any trigger you create will automatically be appended toany existing trigger, rather than erasing it.

• In 60/65 mode, when a batch or procedure contains an invalid object name, awarning is issued when the batch is compiled, letting you know that a refer-enced object does not exist The 70 mode uses deferred resolution, which meansthat SQL Server does not look for the referenced object until the batch is actu-ally run Deferred resolution allows you to create a batch or procedure and thencreate the objects it references later

• In 60/65 mode, an empty string (‘’) is interpreted as a single blank character,which means that DATALENGTH will return a value because it is counting thenumber of spaces in the string In 70 mode, a blank string (‘’) is interpreted asblank, not as a space, so DATALENGTH will not count the blank string as acharacter

• In 60/65 mode, the CHARINDEX and PATINDEX functions return NULL onlywhen both required parameters are null values In 70 mode, these commandsreturn NULL when any of these parameters are set to NULL

• In 60/65 mode, if you reference a text- or image-type column in the inserted ordeleted tables, you will receive a null value in return In 70 mode, references totext and image columns in the inserted and deleted tables are simply notallowed

• In 60/65 mode, the concatenation of null-yields-null-value is off by default,which means that if you try to combine a value with a null, you will receive anempty string in return In 70 mode, the concatenation of null-yields-null is on

by default, meaning that if you combine a value with a null, you will receiveNULL in return

• In 60/65 mode, you can use SELECT statements in the VALUES list of an INSERTstatement In 70 mode, SELECT statements are not allowed in the VALUES list ofthe INSERT statement

Each compatibility-level setting also has its own list of reserved keywords:

Keywords in 70 mode: BACKUP, CONTAINS, CONTAINSTABLE, DENY,FREETEXT, FREETEXTTABLE, PERCENT, RESTORE, ROWGUIDCOL, TOP

Keywords in 60/65 mode: AUTHORIZATION, CASCADE, CROSS, TRIBUTED, ESCAPE, FULL, INNER, JOIN, LEFT, OUTER, PRIVILEGES,RESTRICT, RIGHT, SCHEMA, WORK

Trang 25

Now that you know how to modify your database to behave the way you want it

to, you are ready to start filling it with data Once your users start working with thedatabase, you may find the need to resize it Let’s look at how to do that next

Changing Database Size

Once you put your database in production and your users start filling it with data,you will eventually find the need to resize the database—making it bigger if it turnsout to be very popular, or smaller if it is not used as much as anticipated Let’s look athow to expand the original database file first

Expanding a Data File

If the database you created turns out to be more popular than you expected and yourusers are constantly adding data to it, you may need to increase the size of the data-base Of course, the easiest way to do this is to allow the database to automaticallygrow, like you did with the MAXSIZE and FILEGROWTH options on the sales data-base However, when the database hits the size restriction you set for it, you may need

to expand it still further There are two ways to accomplish this: by increasing the size

of the existing data file or by adding secondary data files

To increase the size of the sales database, use the following steps:

1 Open Enterprise Manager, expand Databases under your server, right-click the

sales database, and select Properties

2 Select the Data Files tab and enter 15 in the Space Allocated column.

3 Under Restrict File Growth, enter 20

Ngày đăng: 21/01/2014, 08:20

TỪ KHÓA LIÊN QUAN