Академический Документы
Профессиональный Документы
Культура Документы
Creating Databases
Databases are usually created either by writing and executing T-SQL code, or through the
graphical interface.
CREATE DATABASE SampleDB
Executing this Transact-SQL will cause SQL Server to create a single database data file and one
In the Database name field, enter the name of the new database. A database name can be a maximum of 128 characters long. A database name must start with a letter or underscore, and then subsequent characters can
be a combination of letters, numbers, and some special characters, but this requirement is not enforced. However, data applications may be unable to make the connection to a database if the name does not conform to accepted standards, so not to deviate from them. Database names should be as descriptive as possible, but also kept as short as possible. Embedded spaces in object names are also problematic, because they can cause unexpected problems when the database is accessed programmatically.
In the Owner field you should typically specify SA, which is the built-in SQL Server
System Administrator account. The default owner is the login account that performs the database creation. The owner of the database gains complete control of the database. Database ownership can be modified by executing the sp_changedbowner stored procedure and specifying any valid login.
USE <database_name> GO sp_changedbowner SA
To retrieve information about databases, the sp_helpdb stored procedure can be used.
The results of the stored procedure when executed with the database name are shown:
To retrieve basic information about all databases the sp_helpdb stored procedure can be executed alone.
USE Master GO EXEC sp_helpdb
Leave the Use full-text indexing box unchecked. Full-text indexing can be enabled at any
time, not just at database creation. Full-text indexing allows for the use of more flexible string-matching queries than TransactSQL strictly allows, and is managed through the Microsoft Full-Text Engine for SQL Server (MSFTESQL) service. Though full-text indexing offers some very flexible and useful tools, it is not always necessary, and should only be turned on when needed.
Database Files:
In the Database files section of the New Database dialog, the Logical Name of the first
data file, as well as the Logical Name for the first log file, have been given names automatically. The first data file is named the same as the database and the log file is given the name of the database with _log appended to the end. The logical names are the names the files can be referred to programmatically. Multiple files can be specified in the creation process. Every file contains its own configuration settings (such as for initial size and growth behavior). The file type is automatically populated and cannot be changed once the file has been added to the database. Click the Add button at the bottom of the New Database dialog. A new row for an additional file is added to the Database files section. The new row defaults to a data type file, but it can be changed.
Type in a Logical Name for the new data file and then in the Filegroup column, click the dropdown list and choose <new filegroup>. The New Filegroup dialog displays.
File Groups:
Databases are created on files that are organized in filegroups.
The only required filegroup is the one called Primary. Filegroups are a logical grouping of data files that will hold the database objects defined for
the database. The Primary filegroup contains all the system references for the database. This is where the objects defined in the Resource database are presented for user databases, as well as any system created objects. The Primary filegroup also contains all the object definitions for user-defined objects. In addition to the Primary filegroup, more user-defined filegroups can be created as needed. one of the biggest advantages of user-defined filegroups : control. With user-defined filegroups, the database administrator has complete control over what data is in what location.
Without user-defined filegroups, all data is stored in the Primary filegroup, so the flexibility and
scalability of the database is reduced. This may be perfectly acceptable for smaller databases, once the database grows to a large size, it will become increasingly unacceptable to have all the user and system data grouped into the same filegroup. Type in a name for the new filegroup, select the Default checkbox, and click OK. This sets the new userdefined filegroup as the default. All user objects created will be created by default in the new filegroup. This segregates system data from user data, and allows for more control of the database structure. The Read-only checkbox sets the filegroup as read-only. This can be very advantageous when organizing the different objects in a database. The objects that change can be placed in an updatable filegroup, whereas those that never (or seldom) change can be placed in a read-only filegroup.
Maintenance or Performance: File groups provide the ability to improve both the performance and the maintainability of a database by separating data across multiple physical files in groups of tables. The maintenance advantage comes from the ability to back up and restore individual files and filegroups. Performance advantages:
parallel read and write operations that are made possible by separating the data files across multiple
physical devices. filegroups enable is the ability to physically partition large tables across multiple filegroups.
File Size:
In the Initial Size (MB) column, a value should be assigned based on how big the file is expected
Auto Growth:
Click the ellipsis button on the right of the Autogrowth column for the primary data file.
The Change Autogrowth dialog displays. The Change Autogrowth dialog enables the configuration of the maximum size and file growth
setting for each individual file. Ensure the Enable Autogrowth checkbox is checked. Clearing this checkbox sets the filegrowth property to zero.
File growth can be set at a fixed allocation size or a percentage of the existing file size.
As a best practice the Autogrowth option should be set to a sufficiently large enough increment to
minimize the number of file-growths required to accommodate data growth. Restrict the size of the file by selecting the Restricted File Growth (MB) option button and specifying a maximum size. This size cannot be exceeded by automatic or manual file-growth operations.
Path: Either click the ellipses button on the right of the Path column of the New Database dialog for each data file and select a destination folder for each individual file, or simply type in the correct path in the Path column.
Database Options:
Click Options in the Select a page section in the upper-left of the New
Database dialog The Options window displays, enabling the setting of several database options. Collation:
Click the Collation drop-down list and review the different collation settings that are available,
but leave the setting set to <server default>. an instance of SQL Server is assigned a default server collation that determines what characters are supported on the server by default, and how those characters are searched and sorted. Collation settings can also be assigned to the database as well.
Recovery Models: Click the Recovery model drop-down list and review the available choices. The available models that can be set are Full, Bulk-Logged, and Simple.
Use the simple recovery model if the following are all true:
If the database is lost or damaged, you are willing to lose all the updates
You are willing to risk losing some data in the log. You do not want to back up and restore the transaction log, The transaction log is only used for transactional consistency, but no longterm storage of
You are willing to incur the administrative costs of transaction log backups.
For all intents and purposes, there are really only two recovery models, Full and Simple. The Bulk-Logged model is meant only as an accessory to the Full recovery model for use
Bulk-logged recovery should be used only during periods in which you are running large-scale
bulk operations, If you use the full recovery model, you can switch temporarily to the bulk-logged recovery model before you perform bulk operations. the bulk-logged recovery model resembles the full recovery model, except that it minimally logs most bulk operations. the bulk-logged recovery model is intended only for use during bulk operations that allow for minimal logging.
Compatibility Level: Unless you have specific reasons to change the compatibility level, it should be set to SQL Server 2008 (100). The compatibility level option changes the behavior of some database operations, and is only necessary if an instance of SQL Server 2008 is sharing database responsibilities with a previous release of SQL Server.
Other options:
Auto Close:
When a database is first accessed, it is opened. When Auto Close is True, the database will be closed when the last user connected to it closes the connection. This setting is off by default because the act of opening and closing the database on a server platform is unnecessary, and produces unneeded overhead. The exception to this rule is SQL Server Express Edition, because SQL Express is designed to run on a desktop system where resources are more restricted and an open database consumes resources. If no user is connected, those resources can be returned to the system.
Auto Shrink:
When set to True, the Database Engine will periodically examine the total size of all database files and compare it to the amount of data being stored. the Database Engine will perform file-shrink operations on database files. ALTER DATABASE abc
ANSI NULL Default specifies whether or not the default for columns added to a table during a CREATE
When set to True, warnings will be raised by the database engine whenever an aggregate function encounters a null. When set to False, no warnings are raised.
When set to True, the Database Engine will generate statistics for columns. Auto Update Statistics When set to True, the Database Engine will automatically update statistical information on columns to maintain the most efficient query plans possible. Database Read Only This option specifies that no modifications are allowed to the database when set to True.
of creating a database, take a look at how you can script this process so that you dont have to go through the process again. At the top of the New Database dialog is a button called Script,
script that will duplicate all the settings you specified in the graphical interface. This script can then be used to create new databases with the same options simply by changing the logical and physical names of the database and associated files.
Schemas
A database schema is a way to logically group objects such as tables, views,
stored procedures etc. Think of a schema as a container of objects. Every object in SQL Server 2008 exists within a defined schema. A schema is a named collection of database objects that forms a namespace. You can assign a user login permissions to a single schema so that the user can only access the objects they are authorized to access. Schemas can be created and altered in a database, and users can be granted access to a schema.
Like this
Database objects fall within the scope of schema & are essentially owned by the schema.
assigned to a different user first. the easiest solution is to have the dbo user own all the schemas. The dbo user is a built-in user that is mapped to any member of the fixed server role sysadmin. The dbo user always exists, and cannot be dropped, so it is a perfect candidate for schema ownership.
Schema Creation: To create a schema, the only required information is the name of the schema. The ownership of the schema defaults to the user that runs the creation script, but any valid database user can be specified as the owner. The simplest approach is to designate dbo as the owner of the schema, The syntax and an example of the CREATE SCHEMA statement are:
CREATE SCHEMA Schema_Name [ AUTHORIZATION owner ] USE AdventureWorks GO CREATE SCHEMA Operations AUTHORIZATION dbo USE AdventureWorks2008R2; GO CREATE SCHEMA Sprockets AUTHORIZATION Annik CREATE TABLE NineProngs (source int, cost int, partnumber int) GRANT SELECT ON SCHEMA::Sprockets TO Mandar DENY SELECT ON SCHEMA::Sprockets TO Prasanna; GO
Schema Maintenance:
If a schema contains objects it cannot be dropped: DROP SCHEMA Operations ---------------------------------------------------------------------------------------------------Msg 3729, Level 16, State 1, Line 1 Cannot drop schema Operations because it is being referenced by object BrontoDriver. If the object in the schema is still required, it can be transferred to a different schema with the ALTER SCHEMA statement: ALTER SCHEMA Production TRANSFER Operations.BrontoDriver This example alters the schema Production by moving the table BrontoDriver from the Operations schema to the Production schema. Because that was the last object in the schema, it can now be dropped.
This example alters the schema Production by moving the table BrontoDriver from the Operations schema to the Production schema. Because that was the last object in the schema, it can now be dropped. ALTER AUTHORIZATION ON SCHEMA::Operations TO Fred
Tables
Table Architecture:
either a heap or a clustered index. By default, tables are stored in unorganized heaps. As the data is inserted, it is added to the next available row on a data page. There is no attempt to keep the data organized or sorted. Although this arrangement works great for adding data to a table, it is less than an optimum solution when trying to find a particular row or set of rows
Table Indexes
heaps by default. A heap is a table that does not have a clustered index. A table stored as a heap has no enforced physical order, but a clustered index does. As data is added to a table stored as a heap, it will be in inserted order at first as described in the library example. Heaps work very well for storing data, and are very efficient in handling new records, but they are not so great when it comes to finding specific data in a table. This is where indexes come in. SQL Server supports two basic types of indexes: clustered and non-clustered. It also supports XML indexes, which are discussed later in this chapter, but they are quite different from the regular relational indexes that will be
DELL DELL
N N
1419 1459
106 1419 106
Why Use an Index? Use of SQL server indexes provide many facilities such as: Rapid access of information Efficient access of information Enforcement of uniqueness constraints
Types of Indexes SQL Server has two major types of indexes: Clustered Non-Clustered
Clustered
the table or view based on their key values. These are the columns included in the index definition. There can be only one clustered index per table, because the data rows themselves can be sorted in only one order. The only time the data rows in a table are stored in sorted order is when the table contains a clustered index. When a table has a clustered index, the table is called a clustered table. If a table has no clustered index, its data rows are stored in an unordered structure called a heap.
from the data rows. A non-clustered index contains the non-clustered index key values and each key value entry has a pointer to the data row that contains the key value. The pointer from an index row in a non-clustered index to a data row is called a row locator. The structure of the row locator depends on whether the data pages are stored in a heap or a clustered table. For a heap, a row locator is a pointer to the row. For a clustered table, the row locator is the clustered index key.
synonyms
to refer to objects with four-part identifiers:
[[[server.][database].][schema_name].]object_na me As the square brackets show, different parts of this syntax can be omitted, as long as you supply enough to unambiguously identify what you're talking about. For example, all of these might refer to the same object: Server1.AdventureWorks.Production.ProductCate gory AdventureWorks.Production.ProductCategory AdventureWorks..ProductCategory
Server database objects that can be used by database applications instead of their defined two-part, three-part, or four-part schema scoped names. For example, a database application that references a table on one server and a table on another server would typically need to be configured to access the tables using a four-part name. Defining a synonym essentially presents an alias that maps directly to the table without having to fully qualify the table. USE AdventureWorks GO SELECT ProductKey, EnglishProductName, StandardCost FROM dbo.Products Synonyms can be created that reference views, tables,
CREATE SYNONYM [schema_name.]synonym_name FOR object_name e.g. CREATE SYNONYM ProdCat FOR AdventureWorks.Production.ProductCategory SELECT * FROM ProdCat DROP SYNONYM [schema_name.]synonym_name
Important to notice
If you don't specify a schema for the synonym,
then SQL Server uses the current user's default schema. The object doesn't need to exist when you create the synonym, because synonyms are late bound: SQL Server only checks the base object when you actually use the synonym.
created:
Tables Views Stored procedures
Functions
you want to use ALTER TABLE to change something about the ProductCategory table, for example, you need to work with the base table, not with the ProdCat