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

Hướng dẫn học Microsoft SQL Server 2008 part 57 pdf

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

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 813,65 KB

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

Nội dung

If the database uses multiple data files, then the first, or primary, file will contain the system tables.. Creating a database with multiple files To create a database with multiple fil

Trang 1

The file sizes and growth options can be adjusted in code with theALTER DATABASEDDL command

and theMODIFY FILEoption The following code setsNewDB’s data file to manual growth and sets the

size to 25MB:

ALTER DATABASE NewDB MODIFY FILE

(Name = NewDB,

SIZE = 25MB,

MAXSIZE = 2Gb, FILEGROWTH = 0);

To list the databases using code, query the sys.databases catalog view.

Best Practice

Many DBAs detest the default autogrowth settings because the database is locked during an autogrowth

Growing by 1MB per growth is probably far too small and will cause frequent interruptions Another

common error is to set the autogrowth to a percentage As the database grows, so will the growth size For

serious production databases the best solution is to monitor the data size and manually grow the database,

but leave autogrowth on as a safety factor

Using multiple files

Both the data file and the transaction log can be stored on multiple files for improved performance and

to allow for growth Any additional, or secondary, data files have an.ndffile extension by default If

the database uses multiple data files, then the first, or primary, file will contain the system tables.

While it does not enable control over the location of tables or indexes, this technique does reduce the

I/O load on each disk subsystem SQL Server attempts to balance the I/O load by splitting the inserts

among the multiple files according to the free space available in each file As SQL Server balances the

load, rows for a single table may be split among multiple locations If the database is configured for

automatic growth, all of the files will fill up before SQL Server increases the size of the files

Creating a database with multiple files

To create a database with multiple files using Management Studio, add the filename to the file grid in

the Files page of the Database Properties dialog (see Figure 20-3)

To create a database with multiple data files from code, add the file locations to theCREATE DATABASE

DDL command using theONoption:

CREATE DATABASE NewDB

ON

PRIMARY

Trang 2

FIGURE 20-3

Creating a database with multiple files using SQL Server Management Studio

(NAME = NewDB,

FILENAME = ‘e:\SQLData\NewDB.mdf’),

(NAME = NewDB2,

FILENAME = ‘f:\SQLData\NewDB2.ndf’)

LOG ON

(NAME = NewDBLog,

FILENAME = ‘g:\SQLLog\NewDBLog.ldf’),

(NAME = NewDBLog2,

FILENAME = ‘h:\SQLLog\NewDBLog2.ldf’);

Result:

The CREATE DATABASE process is allocating

0.63 MB on disk ‘NewDB’

The CREATE DATABASE process is allocating

1.00 MB on disk ‘NewDB2’

Trang 3

The CREATE DATABASE process is allocating 1.00 MB on disk ‘NewDBLog’

The CREATE DATABASE process is allocating 1.00 MB on disk ‘NewDBLog2’

To list the files for the current database using code, query the sys databases catalog view.

Modifying the files of an existing database

The number of files for an existing database may be easily modified If the data is filling the drive,

another data file can be added to the database by adding it to the database file grid Add the new

filename and location to the database properties file grid in the same way that the files were initially

created

In code, a file can be added to an existing database using theALTER DATABASEDDL command and

theADD FILEoption The file syntax is identical to that used to create a new database The following

code adds a third file toNewDB:

ALTER DATABASE NewDB ADD FILE

(NAME = NewDB3, FILENAME = ‘i:\SQLData\NewDB3.ndf’, SIZE = 10MB,

MAXSIZE = 2Gb, FILEGROWTH = 20);

Result:

Extending database by 10.00 MB on disk ‘NewDB3’

If a file is no longer desired because the disk subsystem is being retired or designated for another use,

one of the data or transaction log files can be deleted by shrinking the file usingDBCC ShrinkFile

and then deleting it in Management Studio by selecting the file and pressing Delete

Using T-SQL code, remove additional files with theALTER DATABASE REMOVE FILEDDL command

The following code removes the data file added earlier:

DBCC SHRINKFILE (NewDB3, EMPTYFILE)

ALTER DATABASE NewDB REMOVE FILE NewDB3;

Result:

DbId FileId CurrentSize MinimumSize UsedPages EstimatedPages - - - -

The fileNewDB3has been removed

Trang 4

Planning multiple filegroups

A filegroup is an advanced means of organizing the database objects By default, the database has a single

filegroup — the primary filegroup By configuring a database with multiple filegroups, new objects

(tables, indexes, and so on) can be created on a specified filegroup This technique can support two

main strategies:

■ Using multiple filegroups can increase performance by separating heavily used tables or

indexes onto different disk subsystems

■ Using multiple filegroups can organize the backup and recovery plan by containing static data

in one filegroup and more active data in another filegroup

Best Practice

Create a single secondary filegroup, I call mine ‘‘Data,’’ and set it as the default filegroup This leaves the

primary filegroup dedicated for system objects

Creating a database with filegroups

To add filegroups to a database using Management Studio, open the Database Properties page from

Object Explorer On the Filegroups page, add the new logical filegroup Then, on the Files page, you

can add the new file and select the filegroup for the new file in the combo box

Using T-SQL, you can specify filegroups for new databases using the Filegroups option The following

code creates theNewDBdatabase with two data filegroups:

CREATE DATABASE NewDB

ON

PRIMARY

(NAME = NewDB,

FILENAME = ‘d:\SQLData\NewDB.mdf’,

SIZE = 50MB, MAXSIZE = 5Gb, FILEGROWTH = 25MB),

FILEGROUP Data DEFAULT

(NAME = NewDBData,

FILENAME = ‘e:\SQLData\NewDBData.ndf’,

SIZE = 100MB, MAXSIZE = 50Gb, FILEGROWTH = 100MB) LOG ON

(NAME = NewDBLog,

FILENAME = ‘f:\SQLLog\NewDBLog.ndf’,

SIZE = 100MB, MAXSIZE = 25Gb, FILEGROWTH = 25MB);

Trang 5

Modifying filegroups

Filegroups are easily modified in a manner similar to how files are modified Using Management Studio,

new filegroups may be added, files may be added or removed from a filegroup, and a filegroup may be

removed if it is empty Emptying a filegroup is more difficult than shrinking a file If there’s data in the

filegroup, shrinking a file will only move the data to another file in the filegroup The tables and indexes

must be dropped from the filegroup before the filegroup can be deleted

With Query Editor and T-SQL code, you can add or drop filegroups using theALTER DATABASE ADD

FILEGROUPorALTER DATABASE REMOVE FILEGROUPcommands, respectively, much as you would

use theADDorREMOVE FILEcommand

Dropping a database

A database may be removed from the server by selecting the database in Object Explorer and selecting

Delete from the context menu

In code, you can remove a database with the DDLDROP DATABASEcommand:

DROP DATABASE NewDB;

There is no undo

Creating Tables

Like all relational databases, SQL Server is table-oriented Once the database is created, the next step is

to create the tables A SQL Server database may include up to 2,147,483,647 objects, including tables,

so there’s effectively no limit to the number of tables you can create

Designing tables using Management Studio

If you prefer working in a graphical environment, Management Studio provides two primary work

sur-faces for creating tables, both of which you can use to create new tables or modify existing ones:

■ The Table Designer tool (see Figure 20-4) lists the table columns vertically and places the column properties below the column grid

■ The Database Designer tool (see Figure 20-5) is more flexible than the Table Designer form in that it can display foreign-key constraints as connections to other tables

Chapter 6, ‘‘Using Management Studio,’’ explains how to launch and navigate these tools.

Each of these tools presents a graphical design of the table Once the design is complete, Management

Studio generates a script that applies the changes to the database When modifying an existing table,

often the script must save the data in a temporary table, drop several items, create the new tables, and

reinsert the data

Trang 6

FIGURE 20-4

Developing the Contact table in the OBXKites sample database using Management Studio’s Table

Designer

Table Designer displays only the column name and data type (with length), and allows nulls in the

column grid While these are the main properties of a column, I personally find it annoying to have to

select each column in order to inspect or change the rest of the properties

Each data type is explained in detail later in this chapter For some data types, thelengthproperty

sets the data length, while other data types have fixed lengths Nulls are discussed in the section

‘‘Creating User-Data Columns,’’ later in this chapter

Once an edit is made to the table design, the Save Change Script toolbar button is enabled This

but-ton displays the actual code that the Table Designer will run if the changes are saved In addition, the

Save Change Script button can save the script to a.sqlfile so the change can be repeated on another

server

For more details about using the Table Designer and Database Designer, see Chapter 6,

‘‘Using Management Studio.’’

Trang 7

FIGURE 20-5

Developing the Customer table in the CHA2 sample database using Management Studio’s Database

Designer

Working with SQL scripts

If you are developing a database for mass deployment or repeatable installations, the benefits of

develop-ing the database schema in scripts become obvious:

■ All the code is in one location Working with SQL scripts is similar to developing an applica-tion with VB.NET or C#

■ The script may be stored in Solutions as a Project using the Solution Explorer In addition, scripts can be stored in Microsoft SourceSafe or another change-management system

■ If a database master script contains all the code necessary to generate the database, then the most current version of the database may be installed without running change scripts or restoring a backup

■ An installation that is a fresh new database, as opposed to a backup or detached database, is beneficial for testing because it won’t have any residual data

Trang 8

Working with scripts does have its drawbacks, however:

■ The T-SQL commands may be unfamiliar and the size of the script may become

overwhelming

■ If the foreign-key constraints are embedded within the table, the table-creation order is very

picky If the constraints are applied after the tables are created, the table-creation order is no

longer a problem; however, the foreign keys are distanced from the tables in the script

■ Changes to the database schema must be made usingALTERscripts, which are either

integrated into the master script or carefully executed in the correct order

■ Management Studio database diagrams are not part of the script

The T-SQL commands for working with objects, including tables, areCREATE,ALTER, andDROP The

followingCREATE TABLEDDL command from the Outer Banks Kite Store sample database creates

theProductCategorytable The table name, including the name of the owner (dbo), is provided,

followed by the table’s columns The final code directs SQL Server to create the tableONtheData

filegroup:

CREATE TABLE dbo.ProductCategory (

ProductCategoryID UNIQUEIDENTIFIER NOT NULL

ROWGUIDCOL DEFAULT (NEWID()) PRIMARY KEY NONCLUSTERED,

ProductCategoryName NVARCHAR(50) NOT NULL,

ProductCategoryDescription NVARCHAR(100) NULL

)

ON [Data];

To list the tables for the current database using code, query the sys.objects catalog view, filtering for type_desc = ‘USER_TABLE’

Best Practice

Iconsider the schema to be code, and as such it should be handled as code and checked into a version

control system Inever develop using the graphic user interfaces in Management Studio I strictly develop

using T-SQL scripts

For extensive examples of building databases and tables with scripts, you can reference this book’s sample databases, which are all developed with scripts and are available on www.sqlserverbible.com

Schemas

A schema is an object that exists purely to own database objects, most likely to segment a large database

into manageable modules, or to implement a segmented security strategy

Trang 9

In previous versions of SQL Server, objects were owned by users Or rather, objects were owned by

schema-objects that were the same as the user-owners, but no one spoke in those terms In SQL Server

2005, the concepts of users and schema were separated Users could no longer own objects

Typically, and by default, objects are owned by thedboschema The schema name is the third part of

the four-part name:

Server.database.schema.object;

When using custom schemas, other thandbo, every query has to specify the schema That’s not a bad

thing, because using a two-part name improves performance, but always typing a long schema is no fun

Best Practice

Creating objects in a schema other than dbo can improve security Getting the correct schema is one

more obstacle that helps prevent SQL injection

To list the schema for the current database using code, query the sys.schemas catalog view.

Column names

SQL Server is very liberal with table and column names, allowing up to 128 Unicode characters and

spaces, as well as both uppercase and lowercase letters Of course, taking advantage of that freedom

with wild abandon will be regretted later when typing the lengthy column names and having to

place brackets around columns with spaces It’s more dangerous to discuss naming conventions with

programmers than it is to discuss politics in a mixed crowd Nevertheless, here’s my two cents

There is a debate over whether table names should be singular or plural The plural camp believes that a

table is a set of rows, just like object-oriented classes, and as such should be named with a plural name

The reasoning often used by this camp is, ‘‘A table of customers is a set of customers Sets include

mul-tiple items, so the table should be named the Customers table, unless you only have one customer, in

which case you don’t need a database.’’

From my informal polling, however, the singular-name view is held by about three-fourths of SQL

Server developers These developers hold that the customer table is the customer set, rather than the

set of customers A set of rows is not called a rows set, but a row set, and because tables are generally

discussed as singular items, saying ‘‘theCustomertable’’ sounds cleaner than ‘‘theCustomerstable.’’

Most (but not all) developers would agree that consistency is more important than the naming

conven-tion itself

Personally, I think that developers choose their naming conventions as a way to distance themselves

from sloppy designs they’ve had to work with in the past Having worked on poorly designed flat-file

databases with plural names, I slightly prefer singular names

Trang 10

Best Practice

Consistency is the database developer’s holy grail The purpose of naming conventions, constraints,

referential integrity, relational design, and even column data type is to bring order and consistency to

the data we use to model reality When faced with a database decision, asking ‘‘Which choice is the most

consistent?’’ is a good step toward a solution

Another issue involving differences in naming is the use of underscores to indicate words within

the name For example, some IT shops insist that the order-detail table be namedORDER_DETAIL

Personally, I avoid underscores except in many-to-many resolution tables Studies have shown that

the use of mixed case, such as in the nameOrderDetail, is easier to read than all lowercase or all

uppercase words

However, studies have also shown that using the underscore is the most readable, and some experts

hold firmly to that position

Here are the database-naming conventions I use when developing databases:

■ Use singular table names with no numbers, and a module prefix if useful

■ For many-to-many resolution tables, usetable_mm_table

■ Set all names in mixed case (MixedCase) with no underscores or spaces

■ For the primary key, use the table name +ID For example, the primary key for the

Customertable isCustomerID

■ Give foreign keys the same name as their primary key unless the foreign key enforces

a reflexive/recursive relationship, such asMotherIDreferring back toPersonIDin

theFamilysample database, or the secondary table has multiple foreign keys to the

same primary key, such as the many-to-many reflexive relationship in theMaterial

sample database (BillofMaterials.MaterialIDtoMaterial.MaterialIDand

BillofMaterials.SourceMaterialIDtoMaterial.MaterialID)

■ Avoid inconsistent abbreviations

■ Organize a large complex database with schemas

■ Use consistent table and column names across all databases For example, always use

LastNamefollowed byFirstName

Filegroups

Apart from the columns, the only information normally supplied when a table is being created is

the name However, the table can be created on a specific filegroup if the database has multiple

filegroups

The OBX Kites database uses two filegroups for data organization purposes All data that is modified

on a regular basis goes into thePrimaryfilegroup This filegroup is backed up frequently Data that is

rarely modified (such as the order priority lookup codes) goes into theStaticfilegroup:

Ngày đăng: 04/07/2014, 09:20

TỪ KHÓA LIÊN QUAN