Tải bản đầy đủ (.pdf) (10 trang)

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

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (813.65 KB, 10 trang )

Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 522
Part IV Developing with SQL Server
The file sizes and growth options can be adjusted in code with the ALTER DATABASE DDL command
and the
MODIFY FILE option. The following code sets NewDB’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
M
any 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
.ndf file 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 the
CREATE DATABASE
DDL command using the ON option:
CREATE DATABASE NewDB
ON
PRIMARY
522
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 523
Creating the Physical Database Schema 20
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’.
523
www.getcoolebook.com

Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 524
Part IV Developing with SQL Server
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 the
ALTER DATABASE DDL command and
the
ADD FILE option. The file syntax is identical to that used to create a new database. The following
code adds a third file to
NewDB:
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 using

DBCC ShrinkFile
and then deleting it in Management Studio by selecting the file and pressing Delete.
Using T-SQL code, remove additional files with the
ALTER DATABASE REMOVE FILE DDL 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

12 5 1280 1280 0 0
The file NewDB3 has been removed.
524
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 525
Creating the Physical Database Schema 20
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
C
reate 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 the
NewDB database 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);
525
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 526

Part IV Developing with SQL Server
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 the
ALTER DATABASE ADD
FILEGROUP
or ALTER DATABASE REMOVE FILEGROUP commands, respectively, much as you would
use the
ADD or REMOVE FILE command.
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 DDL
DROP DATABASE command:
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.
526
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 527
Creating the Physical Database Schema 20
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, the
length property
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
.sql file 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.’’
527
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 528

Part IV Developing with SQL Server
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.
528
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 529
Creating the Physical Database Schema 20
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 using
ALTER scripts, 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, are
CREATE, ALTER,andDROP.The
following
CREATE TABLE DDL command from the Outer Banks Kite Store sample database creates
the
ProductCategory table. 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 table
ON the Data
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
I
consider the schema to be code, and as such it should be handled as code and checked into a version
control system. I
never
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.
529
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 530
Part IV Developing with SQL Server
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 the
dbo schema. The schema name is the third part of
the four-part name:
Server.database.schema.object;
When using custom schemas, other than dbo, 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
C
reating 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,butarow set, and because tables are generally
discussed as singular items, saying ‘‘the
Customer table’’ sounds cleaner than ‘‘the Customers table.’’
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 conventionsasawaytodistancethemselves
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.
530
www.getcoolebook.com
Nielsen c20.tex V4 - 07/23/2009 8:26pm Page 531
Creating the Physical Database Schema 20
Best Practice
C
onsistency 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 named
ORDER_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 name
OrderDetail, 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, use
table_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
Customer table is CustomerID.
■ Give foreign keys the same name as their primary key unless the foreign key enforces
a reflexive/recursive relationship, such as
MotherID referring back to PersonID in
the
Family sample database, or the secondary table has multiple foreign keys to the
same primary key, such as the many-to-many reflexive relationship in the
Material
sample database (BillofMaterials.MaterialID to Material.MaterialID and
BillofMaterials.SourceMaterialID to Material.MaterialID).
■ Avoid inconsistent abbreviations.
■ Organize a large complex database with schemas.
■ Use consistent table and column names across all databases. For example, always use
LastName followed by FirstName.
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 the
Primary filegroup. This filegroup is backed up frequently. Data that is

rarely modified (such as the order priority lookup codes) goes into the
Static filegroup:
531
www.getcoolebook.com

×