Chapter VI, databases and database objects
Summary:
1, understand the composition and characteristics of the database
2, grasp the installation and configuration of SQL Server2008
3, master the method of creating and maintaining databases
4, master of architecture definition and maintenance methods
5, master the creation and maintenance methods partition tables, indexes and views
Section I, database creation and maintenance
1.1, SQL Server Database Overview
History of the development of SQL Server
SQL Server 7.0 (in 1999, officially among the ranks of corporate databases)
SQL Server 2000 (In 2000, on behalf of the product)
SQL Server 2005 (2005, code-named "Yukon")
SQL Server 2008 (in 2008, a major product version)
SQL Server 2012
SQL Server 2014
Features of SQL Server
Protection database query
Spend less time on server management operations
Increase application stability
System execution performance optimization and forecasting
- Version of SQL Server
Enterprise Edition (Enterprise Edition): for enterprise applications to provide comprehensive data platform.
Standard Edition (Standard Edition): to provide support for departmental applications.
Developer Edition (Developer Edition): owned Enterprise Edition features, usage restrictions.
Workgroup Edition (Workgroup Edition): to provide support for each branch applications.
Online (Web Edition): provide a low cost WEB application solutions.
Mobile (Compact) support for mobile devices.
Free Edition (Express): suitable for learning and building small applications.
- Install SQL Server 2008 resource requirements
Minimum hardware requirements
Claim | # 32 | # 64 |
---|---|---|
processor | Pcntium Ⅲ or higher | Itanium, Opteron, Athclon or Xcon have EM64T support / Pcntium |
Processor Speed | 1.0GHz or higher | 1.6GHz or higher |
RAM | 512MB | 512MB |
- Classification in SQL Server database
System database (created automatically)
- master: All system-level information, metadata, endpoints, connections, and system configuration server.
- msdb: save this information when using the agent alarm service scheduling and operations, recording operator.
- tempdb: used to store temporary objects and intermediate results, every time you start re-created.
- model: all template databases, public databases to store user information.
- resource: read-only database. Less than seen in the Object Explorer.
User database (related to data storage and user traffic)
1.2, the composition of the SQL Server database
- SQL Server database mapped to a set of operating system files:
data files
.mdf: primary data file. Only one size no smaller than 3MB.
.ndf: secondary data files. There are 0 or more, can be stored on a disk or multiple disks.
Log Files
.ldf: transaction log file. At least one log file.
1.2.1 distribution, database storage space
When you create a user database, model database is automatically copied to the new library.
The smallest unit of data storage: Data Page (Page, referred to as the page).
1 is an 8KB page of contiguous disk space. (Contiguous storage space)
The page size determines the maximum size of the database table row of data.
Rows can not collapse pages are stored.
1.2.2 Exercise
Example: a data table 10000 rows of data, 3000 bytes per row, calculation table memory space is required.
The answer: 10000/2 * 8KB = 40MB
Space utilization 6000/8000 = 75%
1.3, the database file group
Two types of files Group:
The primary filegroup (PRIMARY)
System definition, contains the main data files and any other data files to other file group is not explicitly assigned, the system tables All pages are allocated in the master file group.
User-defined file group
FILEGROUP designated with the keyword when you define or modify the database.
note:
Log files are not in the group file, log space and data space management separately.
A file can not be more than one file group members.
If the file contains more than one file group, the cycle will automatically increase after all the files are filled.
After the addition of the database file, the file can not be moved to other groups.
You can specify only a file set as the default file groups.
1.4, the database file attributes
Data files and log files defined database of information you need:
File name and location
Logical file name, physical file name
Initial size
You can not be less than the size of the model database primary data file
Growth
You can specify whether a file from growth (default)
The maximum size
The maximum limit file growth. Default Unlimited
Growth
You can specify whether a file from growth (default)
The maximum size
The maximum limit file growth. Default Unlimited
1.5, create a database using T-SQL
There are two general ways to create the database:
By creating a database SQL Server Management Studio (visual creation)
Create a database via T-SQL statements (create console)
T-SQL
CREATE DATABASE database_name
//指定创建的数据库逻辑名 如Studentdb
[ ON
[<filespec> [, … n] ]
[, <filegroup> [,…n] ]
//指定创建的数据库主文件(mdf)存放的路径比如 e:\Studentdb.mdf
]
[
LOG ON {<filespec> [,…n]}
//指定创建的数据库日志文件(ldf)存放的路径比如e:\Studentdb_log.ldf
]
[COLLATE collation_name]
[FOR LOAD| FOR ATTACH]
Description:
PRIMARY: designated as the primary database file, you do not specify a default the first file is the main data file.
LOG ON: automatically create a log file, the total size of the data file 25% or greater of 512KB.
NAME: logical file names only.
FILENAME: physical file name.
SIZE: initial size, .mdf size is not less than the model, .ndf default 1MB.
MAXSIZE: the maximum size is not specified, the file is automatically grows until the disk is full.
UNLIMITED: unlimited growth, generally designated log file 2TB, data files 16TB.
FILEGROWTH: Specifies the files automatically increment, not more than MAXSIZE default data file 1MB, the log file is 10% of the current file.
FILEGROUP: set of logical file name only, it can not be a system name.
DEFAULE: specify the file set as the default file groups.
Case:
CREATE DATABASE Studentdb
//数据库名
ON
( NAME = 'Studentdb_Data',
//主数据文件逻辑名
FILENAME = 'E:\Studentdb.mdf',
//主数据文件存放位置
SIZE = 3MB,
//主数据文件初始大小
MAXSIZE = 50MB,
//主数据文件最大大小
FILEGROWTH = 10%
//超过初始大小后文件增长率
)
LOG ON
( NAME = 'Studentdb_Log',
//日志文件逻辑名
FILENAME = 'E:\ Studentdb.ldf',
//日志文件存放位置
SIZE = 2MB,
//日志文件初始大小
MAXSIZE = 5MB,
//日志文件最大大小
FILEGROWTH = 1MB
//超过初始大小后文件增长率
)
GO
//执行建数据库的命令
1.6, modify the database
Expand the database space
Expand the size of the existing database file
Add a new file for the database
Shrink the database space
That release unused space in the database, shrink the file from the end of the beginning.
Auto shrink: AUTO_SHRINK, default false.
Hand shrink: shrink the database in a file size;
Shrink in proportion to the size of the entire database.
Adding and deleting database files
ALTER DATABASE DATABASE
{ ADD FILE < filespec > [ ,...n ] [ TO FILEGROUP filegroup_name ]
| ADD LOG FILE < filespec > [ ,...n ]
| REMOVE FILE logical_file_name
| ADD FILEGROUP filegroup_name
| REMOVE FILEGROUP filegroup_name
| MODIFY FILE < filespec >
| MODIFY NAME = new_dbname
| MODIFY FILEGROUP filegroup_name {filegroup_property
| NAME = new_filegroup_name }
| SET < optionspec > [ ,...n ] [ WITH < termination > ]
| COLLATE < collation_name >
}
Expand the size of the specified file:
ALTER DATABASE STU_DB
MODIFY FILE(NAME=student_data, SIZE=8MB)
Add a new data file:
ALTER DATABASE STU_DB
ADD FILE(NAME=student_data2,
FILENAME=‘E:\Data\student_data2.ndf’,
SIZE=6MB,FILEGROWTH=0)
Shrink the size of the entire database:
DBCC SHRINKDATABASE
Shrink the size of the specified file:
DBCC SHRINKFILE
Example 1:
DBCC SHRINKDATABASE(students,20)
Shrinkage a database file has used 20% of free space
Example 2:
DBCC SHRINKFILE(students_data1,4)
Shrink the database size to 4MB
Delete the database files:
ALTER DATABASE STU_DB
REMOVE FILE student_log1
note:
When you add a file, the data files in each group to fill proportion, the log file is sequentially increased.
To delete the file is empty.
1.7, detaching and attaching databases
Detach the database
Role: to achieve the database to another from one database server does not need to rebuild.
Deleted from the instance, it does not delete data files and log files to keep data files and log files are complete and consistent.
Use sp_detach_db system stored procedures
如:EXEC sp_detach_db‘student’,‘true’
Additional database
The separated reattach the database management system to the database.
You must specify the primary data file of physical storage location and file name.
CREATE DATABASE ……
FOR ATTACH|ATTACH_REBUILD_LOG
Example:
CREATE DATABASE students
On(FILENAME=‘F:\Data\Students_data1.mdf’)
FOR ATTACH
Section II, architecture
Architecture (Schema, also known as pattern) , is a logical namespace of the database, the database is a container object, a database that contains one or more of the framework, within the same database schema name unique.
Defined framework
CREATE SCHEMA [<构架名>]
AUTHORIZATION<用户名>
Delete framework
DROP SCHEMA [<构架名>]
Section III, the partition table
3.1, Basic Concepts
Partition table is a data table is divided horizontally into different subsets, the subset of the data stored in a database one or more file groups. Physically large table into several smaller tables, logic, or a large table.
The rational use of partitions can improve database performance.
Create a partition table depends on whether the current data size, and the amount of data in the future, but also on the operating characteristics of the data in the table.
Table contains large amounts of data using a number of different ways (or will contain)
Data are segmented, such as in the year separated.
3.2, create a partition table
Three steps:
(1) Create a partition function: tell the DBMS (database management system) in what way partition
CREATE PARTITION FUNCTION
(2) create a partition scheme: partitioning function is to map the role of partitioning the generated file to the group
CREATE PARTITION SCHEME
(3) the use of partitions to create a table
Column title:
Example 1:
Create a partition function on the left side of the partitioning column coll (int):
CREATE PARTITION FUCNTION myPF1(int)
AS RANGE LEFT FOR VALUES(1,100,1000);
Partition | 1 | 2 | 3 | 4 |
---|---|---|---|---|
value | col1<=1 | col1>1 AND col1<=100 | col1>100 AND col1<=1000 | col1>1000 |
If you are using the right side of the partition
CREATE PARTITION FUCNTION myPF1(int)
AS RANGE RIGHT FOR VALUES(1,100,1000);
Partition | 1 | 2 | 3 | 4 |
---|---|---|---|---|
value | col1<1 | col1>=1 AND col1<100 | col1>=100 AND col1<1000 | col1>=1000 |
Example 2:
Create a partition function first, then create a partition scheme, and created with the partition table.
//创建分区函数
CREATE PARTITION FUCNTION myPF1(int) AS RANGE LEFT FOR VALUES(1,100,1000);
GO
//创建分区方案
CREATE PARTITION SCHEME myPS1 AS PARTITION myPF1 TO (
test1fg, test2fg, test3fg, test4fg)
GO
CREATE TABLE PartitionTable(
Coll int,
Col2 char(10)
ON myPS1(coll))
Explanation:
CREATE PARTITION SCHEME myPS1 AS PARTITION myPF1 // partition function of the TO (
test1fg, test2fg, test3fg, test4fg // four groups of files)
TABLE PartitionTable the CREATE (
Coll. Int,
Col2 char (10)
the ON myPS1 (Coll) // partition of the row)
The fourth quarter, the index
4.1, create an index
CREATE [UNIQUE] [CLUSTERED|NONCLUSTERED]
INDEX index_name
ON table_name(column_name…)
//填充因子(系数):指定一个0~100之间的值,表示索引页填充的百分比
[WITH FILLFACTOR=x]
INDEX: Index Keywords
UNIQUE represents a unique index, optional
CLUSTERED, NONCLUSTERED represents the clustered index or non-clustered index,
Alternatively FILLFACTOR percentage represents the fill factor, a specified value between 0 and 100, indicating that the index pages to fill the space occupied by
4.2, delete the index
DROP INDEX
// index of the column where the table or indexed view, and index names to be deleted
'tablename.indexname|viewtable.indexname'
// indicates the index to be deleted can specify multiple
[,...n]
Chapter V, indexed views
5.1, Basic Concepts
Standard view, also known as virtual tables to return a result set with the same base table. The results set is not stored permanently standard view;
Create a unique clustered index of view, called indexed view , also known as materialized views. After indexing, the view of the result set is stored in the database .
Changes to the base table will be reflected in the data stored in the index view.
5.2, Occasion indexed view
Few update the underlying data, indexed views better
If the underlying data in batch form is updated regularly, and is mainly treated as read-only data, consider deleting all indexed views before updating, then rebuild, improve update performance.
- Indexed views can improve the performance of these types of queries
Processing large numbers of rows and polymeric connections
Connecting many queries and aggregation operations commonly performed
- Indexed views typically do not improve the performance of these types of queries
A large number of write operations OLTP system
With a large number of database update operations
The polymerization does not involve queries or linked
GROUP BY base data having a high degree of polymerization.
5.3, the definition of an indexed view
- Create a clustered index on the view before conditions must be met:
When you define an indexed view, the view can only refer to a base table, not other views.
So referenced base tables and views in the same database , same owner.
Must SCHEMABINDING option to build view.
All functions referenced in the view of the expression must be determined.
The first index created on a view is unique clustered index , created after the other.
CREATE VIEW;WITH SCHEMABINDING; CREATE
UNIQUE CLUSTERED INDEX …
example:
1、
1、在SQL Server 2008中,主要数据文件必须建立在( )文件组中。
答案:主
2、
2、不同的数据库管理系统采用的日志文件格式不完全一样,概括起来主要有以记录为单位的日志文件和以( )为单位的日志文件两种。
答案:数据块
3、
3、在SQL Server 2008中,每个数据页可存储8060字节的数据。设表T有10000行数据,每行占用4031字节,则存储该表数据大约需要( )MB存储空间,其空间利用率大约是( )%。(存储空间和空间利用率均保留到整数,小数点后按四舍五入处理)
解:行数据不能跨页存储
4031<8060<4031*2,所以每个页只能存储1行数据
10000*1*8(每页的大小8KB)=80000KB=80MB
[4031/8060]=0.5=50%
答案:80、50
4、
4、在SQL Server 2008中,如果数据库tempdb的空间不足,可能会造成一些操作无法进行,此时需要扩大tempdb的空间。下列关于扩大tempdb空间的方法,错误的是( )
A.手工扩大tempdb中某数据文件的大小
B.设置tempdb中的数据文件为自动增长方式,每当空间不够时让其自动增长
C.手工为tempdb增加一个数据文件
D.删除tempdb中的日志内容,以获得更多的数据空间
答案:D[删除文件,必须是文件内容为空的时候]
5、
5、设有职工表(职工号,姓名,地址1,地址2),其中,职工号为主码。现要求地址1和地址2组合起来不能有重复值。在SQL Server 2008环境中有下列创建该表的语句:
Ⅰ.CREATE TABLE 职工表(
职工号 int PRIMARY KEY,
姓名 nchar(10),
地址1 nvarchar(20),
地址2 nvarchar(20),
UNIQUE(地址1,地址2)
)
Ⅱ.CREATE TABLE 职工表(
职工号 int PRIMARY KEY,
姓名 nchar(10),
地址1 nvarchar(20),
地址2 nvarchar(20)UNIQUE(地址1,地址2)
)
Ⅲ.CREATE TABLE 职工表(
职工号 int PRIMARY KEY,
姓名 nchar(10),
地址1 nvarchar(20)UNIQUE,
地址2 nvarchar(20)UNIQUE
)
Ⅳ.CREATE TABLE 职工表(
职工号 int PRIMARY KEY,
姓名 nchar(10),
地址1 nvarchar(20) UNIQUE(地址1,地址2),
地址2 nvarchar(20)
)
上述语句能正确实现此约束的是( )
A.仅Ⅰ和Ⅲ
B.仅Ⅱ和Ⅳ
C.都正确
D.仅Ⅰ、Ⅱ和Ⅳ
答案:D
两个地址不能相同的约束语句是:
UNIQUE(地址1,地址2)
6、
6、在进行数据库物理设计时,为提高查询效率,需要在基本表的一些列上建立索引。有下列情况:
Ⅰ.查询语句的WHERE子句中引用率比较高的列
Ⅱ.经常参与连接操作的列
Ⅲ.经常在order by子句中出现的列
Ⅳ.经常使用LIKE操作符且字符串前后均带有%的列
上述情况中一般情况下适合建立索引的是( )
A.以上全部
B.仅Ⅰ和Ⅲ
C.仅Ⅱ、Ⅲ和Ⅳ
D.仅Ⅰ、Ⅱ和Ⅲ
答案:D