36
8/4/2019 03 27 2008 Create Database http://slidepdf.com/reader/full/03-27-2008-create-database 1/36 03/27/2008: 1. SQL Server Configuration manager 2. Surface area connection manager 3. Server Properties: Sp_configure 4. Startup Parameters: C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\ sqlservr.exe Singile user mode: sqlservr.exe - m -s <instancename> Minimal Configuration: sqlservr.exe - f -s <instancename> Default startup options Description -d master_file_path The fully qualified path for the master database file (typically, C:\Program Files\Microsoft SQL Server\MSSQL\Data\Master.mdf). If you do not provide this option, the existing registry parameters are used. -e error_log_path The fully qualified path for the error log file (typically, C:\Program Files\Microsoft SQL Server\MSSQL\Log\Errorlog). If you do not provide this option, the existing registry parameters are used. -l master_log_path The fully qualified path for the master database log file (typically C:\Program Files\Microsoft SQL Server\MSSQL\Data\Mastlog.ldf). -f 

03 27 2008 Create Database

  • Upload
    gkmeka

  • View
    217

  • Download
    0

Embed Size (px)

Citation preview

Page 1: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 1/36

03/27/2008:

1. SQL Server Configuration manager

2. Surface area connection manager

3. Server Properties:

Sp_configure

4. Startup Parameters:

C:\Program Files\Microsoft SQL Server\MSSQL.1\MSSQL\Binn\ sqlservr.exe

Singile user mode: sqlservr.exe - m -s <instancename>

Minimal Configuration: sqlservr.exe - f -s<instancename>

Default startupoptions

Description

-d master_file_path

The fully qualified path for the masterdatabase file (typically, C:\ProgramFiles\Microsoft SQLServer\MSSQL\Data\Master.mdf). If you donot provide this option, the existing registryparameters are used.

-e error_log_path

The fully qualified path for the error log file(typically, C:\Program Files\Microsoft SQLServer\MSSQL\Log\Errorlog). If you do notprovide this option, the existing registryparameters are used.

-l master_log_path

The fully qualified path for the masterdatabase log file (typically C:\Program

Files\Microsoft SQLServer\MSSQL\Data\Mastlog.ldf).

-f 

Page 2: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 2/36

-gmemory_to_reserve

-h

-m

-n

-s

-T trace#

Indicates that an instance of SQL Servershould be started with a specified trace flag(trace#) in effect. Trace flags are used to

start the server with nonstandard behavior.For more information, see Trace Flags(Transact-SQL).

-xDisables the keeping of CPU time and cache-hit ratio statistics. Allows maximumperformance.

Note:

When specifying a trace flag with the -T option, use an uppercase

"T" to pass the trace flag number. A lowercase "t" is accepted bySQL Server, but this sets other internal trace flags that are requiredonly by SQL Server support engineers. (Parameters specified in theControl Panel startup window are not read.)

Database Creation:

File Groups:

Data Files:mdf/ndf 

Page 3: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 3/36

In SQL Server, the page size is 8 KB. This means SQL Serverdatabases have 128 pages per megabyte. Each page begins with a96-byte header that is used to store system information about thepage. This information includes the page number, page type, theamount of free space on the page, and the allocation unit ID of theobject that owns the page.

The following table shows the page types used in the data files of aSQL Server database.

Page type Contents

Data

Data rows with all data, except text, ntext,image, nvarchar(max), varchar(max),varbinary(max), and xml data, when text inrow is set to ON.

Index Index entries.

Text/Image Large object data types:

• text, ntext, image, nvarchar(max),varchar(max), varbinary(max), and xmldata

Variable length columns when the data rowexceeds 8 KB:

Page 4: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 4/36

• varchar, nvarchar, varbinary, andsql_variant 

Global Allocation

Map, Shared GlobalAllocation Map

Information about whether extents are

allocated.

Page Free SpaceInformation about page allocation and freespace available on pages.

Index AllocationMap

Information about extents used by a table orindex per allocation unit.

Bulk Changed Map

Information about extents modified by bulk

operations since the last BACKUP LOGstatement per allocation unit.

Differential ChangedMap

Information about extents that have changedsince the last BACKUP DATABASE statement perallocation unit.

Note:

Log files do not contain pages; they contain a series of log records.

Data rows are put on the page serially, starting immediately afterthe header. A row offset table starts at the end of the page, andeach row offset table contains one entry for each row on the page.

Each entry records how far the first byte of the row is from the startof the page. The entries in the row offset table are in reversesequence from the sequence of the rows on the page.

Page 5: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 5/36

Surpassing the 8,060-byte row-size limit might affect performance

because SQL Server 2005 Database Engine still maintains a limit of 

8 KB per page. When a combination of varchar, nvarchar,

varbinary, sql_variant, or CLR user-defined type columns exceeds

this limit, the Database Engine moves the record column with the

largest width to another page in the ROW_OVERFLOW_DATA

allocation unit, while maintaining a 24-byte pointer on the original

page. Moving large records to another page occurs dynamically asrecords are lengthened based on update operations. Update

operations that shorten records may cause records to be moved

back to the original page in the IN_ROW_DATA allocation unit. Also,

querying and performing other select operations, such as sorts or

 joins on large records that contain row-overflow data slows

processing time, because these records are processed

synchronously instead of asynchronously.

Extents

Extents are the basic unit in which space is managed. An extent iseight physically contiguous pages, or 64 KB. This means SQL Serverdatabases have 16 extents per megabyte.

Page 6: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 6/36

To make its space allocation efficient, SQL Server does not allocatewhole extents to tables with small amounts of data. SQL Server hastwo types of extents:

• Uniform extents are owned by a single object; all eight pages

in the extent can only be used by the owning object.

• Mixed extents are shared by up to eight objects. Each of theeight pages in the extent can be owned by a different object.

A new table or index is generally allocated pages from mixedextents. When the table or index grows to the point that it has eightpages, it then switches to use uniform extents for subsequentallocations. If you create an index on an existing table that has

enough rows to generate eight pages in the index, all allocations tothe index are in uniform extents.

CREATE DATABASE database_name

[ ON[ PRIMARY ] [ <filespec> [ ,...n ][ , <filegroup> [ ,...n ] ]

[ LOG ON { <filespec> [ ,...n ] } ]][ COLLATE collation_name ][ WITH <external_access_option> ]

Page 7: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 7/36

][;]

 <filespec>  ::= 

{(

NAME = logical_file_name ,FILENAME = 'os_file_name' 

[ , SIZE = size [ KB | MB | GB | TB ] ][ , MAXSIZE = { max_size [ KB | MB | GB | TB ] |

UNLIMITED } ][ , FILEGROWTH = growth_increment [ KB | MB | GB

| TB | % ] ]) [ ,...n ]

}

 <filegroup> ::={FILEGROUP filegroup_name [ DEFAULT ]

<filespec> [ ,...n ]}

Examples:

USE master;GOIF DB_ID (N'FirstDB') IS NOT NULLDROP DATABASE FirstDB;GOCREATE DATABASE FirstDB;

Page 8: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 8/36

GO-- Verify the database files and sizes

SELECT name, size, size*1.0/128 AS [Size in MBs]FROM sys.master_files

 WHERE name = N'mytest';GO

CREATE DATABASE SalesON PRIMARY( NAME = Sales_dat,  FILENAME =  'F:\MSSQL\Data\saledat.mdf',  SIZE = 10,  MAXSIZE = 50,  FILEGROWTH = 5 ),( NAME = Sales_dat2,  FILENAME =  'G:\MSSQL\LOGS\saledat2.ndf',  SIZE = 10,  MAXSIZE = 50,  FILEGROWTH = 5 )LOG ON( NAME = Sales_log,  FILENAME = 'G:\MSSQL\LOGS\salelog.ldf',  SIZE = 5MB,  MAXSIZE = 25MB,  FILEGROWTH = 5MB )

CREATE DATABASE SalesON PRIMARY

( NAME = Sales_dat,  FILENAME =  'F:\MSSQL\Data\saledat.mdf',  SIZE = 10,  MAXSIZE = 50,  FILEGROWTH = 5 ),FILEGROUP ACCOUNT( NAME = Sales_dat2,  FILENAME =  'G:\MSSQL\LOGS\saledat2.ndf',  SIZE = 10,  MAXSIZE = 50,  FILEGROWTH = 5 )LOG ON( NAME = Sales_log,  FILENAME = 'G:\MSSQL\LOGS\salelog.ldf',  SIZE = 5MB,  MAXSIZE = 25MB,  FILEGROWTH = 5MB )

Page 9: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 9/36

By Using FOR Attach Clause:

Dettach it first:

CREATE DATABASE ArchiveON 

(FILENAME =  'F:\MSSQL\Data\saledat.mdf'),(FILENAME =  'F:\MSSQL\Data\saledat2.ndf')FOR ATTACH

Rebuild Log:

************************************

Alter database:

ADD/MODIFY Files

ALTER DATABASE database_name{

<add_or_modify_files> 

 <add_or_modify_files>::={

ADD FILE <filespec> [ ,...n 

][ TO FILEGROUP { filegroup_name | DEFAULT } ]| ADD LOG FILE <filespec> [ ,...n ]| REMOVE FILE logical_file_name | MODIFY FILE <filespec>

}

 <filespec>::=(

NAME = logical_file_name

[ , NEWNAME = new_logical_name ][ , FILENAME = 'os_file_name' ][ , SIZE = size [ KB | MB | GB | TB ] ][ , MAXSIZE = { max_size [ KB | MB | GB | TB ] |

UNLIMITED } ][ , FILEGROWTH = growth_increment [ KB | MB | GB |

TB| % ] ]

Page 10: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 10/36

[ , OFFLINE ]) 

ALTER DATABASE ARchiveADD FILE (  NAME = Test1dat2,  FILENAME = 'F:\MSSQL\Data\SqlesData3.ndf',  SIZE = 5MB,  MAXSIZE = 100MB,  FILEGROWTH = 5MB) TO FILEGROUP ACCOUNT

ALTER DATABASE ARchiveADD LOG FILE (  NAME = Test1log2,

  FILENAME = 'G:\MSSQL\logs\Sqleslog.ldf',  SIZE = 5MB,  MAXSIZE = 100MB,  FILEGROWTH = 5MB) 

ALTER DATABASE ARchiveREMOVE FILE Test1log2

ALTER DATABASE ARchiveMODIFY FILE (NAME = 'Test1dat2',NEWNAME = 'sales_dat3')

ALTER DATABASE ArchiveMODIFY FILE  (NAME = Salesdat4,  SIZE = 20MB);

Moving files from one location to another location:

Run the command and take off line and copy and then online.

ALTER DATABASE Archive

MODIFY FILE(  NAME = Salesdat3,  FILENAME = N'F:\Salesdat3.ndf');

Page 11: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 11/36

 ADD/MODIFY File groups

ALTER DATABASE database_name{| <add_or_modify_filegroups> 

 <add_or_modify_filegroups>::={

| ADD FILEGROUP filegroup_name| REMOVE FILEGROUP filegroup_name| MODIFY FILEGROUP filegroup_name

{ <filegroup_updatability_option> | DEFAULT| NAME = new_filegroup_name 

}} <filegroup_updatability_option>::={

{ READONLY | READWRITE }| { READ_ONLY | READ_WRITE }

}

ALTER DATABASE ARchiveADD FILEGROUP SALES;

ALTER DATABASE ARchiveADD FILEGROUP TEST;

ALTER DATABASE ARchiveREMOVE FILEGROUP TEST;

ALTER DATABASE ArchiveMODIFY FILEGROUP Account DEFAULT;

ALTER DATABASE ArchiveMODIFY FILEGROUP SalesNAME = Sales1

ALTER DATABASE ArchiveMODIFY FILEGROUP Sales1READ_ONLY 

Page 12: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 12/36

ALTER DATABASE ArchiveMODIFY FILEGROUP Sales1READ_WRITE

SET Options BY USING ALTER:

ALTER DATABASE database_name{| <set_database_options> 

}[;]

 <set_database_options>::=SET{

{ <optionspec> [ ,...n ] [ WITH <termination> ] }| ALLOW_SNAPSHOT_ISOLATION {ON | OFF }| READ_COMMITTED_SNAPSHOT {ON | OFF } [ WITH

<termination> ]}

 <optionspec>::= {

<db_state_option>| <db_user_access_option>| <db_update_option>| <external_access_option>| <cursor_option>| <auto_option>| <sql_option>| <recovery_option>| <database_mirroring_option>| <supplemental_logging_option>| <service_broker_option>| <date_correlation_optimization_option>| <parameterization_option>

}

 <db_state_option> ::={ ONLINE | OFFLINE | EMERGENCY }

 <db_user_access_option> ::=

Page 13: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 13/36

{ SINGLE_USER | RESTRICTED_USER | MULTI_USER }

 <db_update_option> ::={ READ_ONLY | READ_WRITE }

 <external_access_option> ::=DB_CHAINING { ON | OFF }

| TRUSTWORTHY { ON | OFF }

} <cursor_option> ::={ CURSOR_CLOSE_ON_COMMIT { ON | OFF }| CURSOR_DEFAULT { LOCAL | GLOBAL }

}

 <auto_option> ::={

AUTO_CLOSE { ON | OFF }| AUTO_CREATE_STATISTICS { ON | OFF }| AUTO_SHRINK { ON | OFF }| AUTO_UPDATE_STATISTICS { ON | OFF }| AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }

}

ALTER DATABASE ArchiveSET EMERGENCY

ALTER DATABASE ArchiveSET ONLINE

ALTER DATABASE ArchiveSET ONLINE,MULTI_USER

ALTER DATABASE ArchiveSET ONLINE,MULTI_USER,READ_ONLY

ALTER DATABASE ArchiveSET ONLINE,MULTI_USER,READ_WRITE

Page 14: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 14/36

<db_state_option>::=

Controls the state of the database.

OFFLINE

The database is closed, shut down cleanly, and marked offline.The database cannot be modified while it is offline.

ONLINE

The database is open and available for use.

EMERGENCY

The database is marked READ_ONLY, logging is disabled, andaccess is limited to members of the sysadmin fixed serverrole. EMERGENCY is primarily used for troubleshootingpurposes. For example, a database marked as suspect can beset to the EMERGENCY state. This could enable the systemadministrator read-only access to the database. Only membersof the sysadmin fixed server role can set a database to theEMERGENCY state.

The status of this option can be determined by examining the stateand state_desc columns in the sys.databases catalog view or theStatus property of the DATABASEPROPERTYEX function. For moreinformation, see Database States.

<db_user_access_option> ::=

Controls user access to the database.

SINGLE_USERSpecifies that only one user at a time can access the database.If SINGLE_USER is specified and there are other usersconnected to the database the ALTER DATABASE statementwill be blocked until all users disconnect from the specified

Page 15: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 15/36

database. To override this behavior, see the WITH<termination> clause.

The database remains in SINGLE_USER mode even if the userthat set the option logs off. At that point, a different user, but

only one, can connect to the database.

RESTRICTED_USER

RESTRICTED_USER allows for only members of the db_ownerfixed database role and dbcreator and sysadmin fixed serverroles to connect to the database, but does not limit theirnumber. All connections to the database are disconnected inthe timeframe specified by the termination clause of the ALTERDATABASE statement. After the database has transitioned to

the RESTRICTED_USER state, connection attempts byunqualified users are refused.

MULTI_USER

All users that have the appropriate permissions to connect tothe database are allowed.

The status of this option can be determined by examining theuser_access column in the sys.databases catalog view or theUserAccess property of the DATABASEPROPERTYEX function.

<db_update_option>::=

Controls whether updates are allowed on the database.

READ_ONLY

Users can read data from the database but not modify it.

READ_WRITE

The database is available for read and write operations.

To change this state, you must have exclusive access to thedatabase. For more information, see the SINGLE_USER clause.

<external_access_option>::=

Page 16: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 16/36

Page 17: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 17/36

By default, the master database has TRUSTWORTHY set toON. The model and tempdb databases always haveTRUSTWORTHY set to OFF, and the value cannot be changedfor these databases.

To set this option, requires membership in the sysadmin fixedserver role.

The status of this option can be determined by examining theis_trustworthy_on column in the sys.databases catalogview.

<cursor_option>::=

Controls cursor options.

CURSOR_CLOSE_ON_COMMIT { ON | OFF }ON

Any cursors open when a transaction is committed or rolledback are closed.

OFF

Cursors remain open when a transaction is committed; rollingback a transaction closes any cursors except those defined as

INSENSITIVE or STATIC.

Connection-level settings that are set by using the SETstatement override the default database setting forCURSOR_CLOSE_ON_COMMIT. By default, ODBC and OLE DBclients issue a connection-level SET statement settingCURSOR_CLOSE_ON_COMMIT to OFF for the session whenconnecting to an instance of SQL Server. For moreinformation, see SET CURSOR_CLOSE_ON_COMMIT (Transact-SQL).

The status of this option can be determined by examining theis_cursor_close_on_commit_on column in thesys.databases catalog view or theIsCloseCursorsOnCommitEnabled property of theDATABASEPROPERTYEX function.

Page 18: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 18/36

CURSOR_DEFAULT { LOCAL | GLOBAL }

Controls whether cursor scope uses LOCAL or GLOBAL.

LOCAL

When LOCAL is specified and a cursor is not defined asGLOBAL when created, the scope of the cursor is local to thebatch, stored procedure, or trigger in which the cursor wascreated. The cursor name is valid only within this scope. Thecursor can be referenced by local cursor variables in the batch,stored procedure, or trigger, or a stored procedure OUTPUTparameter. The cursor is implicitly deallocated when the batch,stored procedure, or trigger ends, unless it was passed back inan OUTPUT parameter. If the cursor is passed back in anOUTPUT parameter, the cursor is deallocated when the lastvariable that references it is deallocated or goes out of scope.

GLOBAL

When GLOBAL is specified, and a cursor is not defined asLOCAL when created, the scope of the cursor is global to theconnection. The cursor name can be referenced in any storedprocedure or batch executed by the connection.

The cursor is implicitly deallocated only at disconnect. For

more information, see DECLARE CURSOR (Transact-SQL).

The status of this option can be determined by examining theis_local_cursor_default column in the sys.databasescatalog view or the IsLocalCursorsDefault property of theDATABASEPROPERTYEX function.

AUTO_SHRINK { ON | OFF }ON

The database files are candidates for periodic shrinking.

Both data file and log files can be automatically shrunk.AUTO_SHRINK reduces the size of the transaction log only if the database is set to SIMPLE recovery model or if the log isbacked up. When set to OFF, the database files are notautomatically shrunk during periodic checks for unused space.

Page 19: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 19/36

The AUTO_SHRINK option causes files to be shrunk when morethan 25 percent of the file contains unused space. The file isshrunk to a size where 25 percent of the file is unused space,or to the size of the file when it was created, whichever is

larger.You cannot shrink a read-only database.

OFF

The database files are not automatically shrunk during periodicchecks for unused space.

The status of this option can be determined by examining theis_auto_shrink_on column in the sys.databases catalog

view or the IsAutoShrink property of theDATABASEPROPERTYEX function. .

AUTO_UPDATE_STATISTICS { ON | OFF }ON

Any out-of-date statistics required by a query for optimizationare automatically updated during query optimization.

OFF

Statistics must be manually updated.

Note:

The UPDATE STATISTICS statement reenables automatic statisticalupdating on the target table or view unless the NORECOMPUTEclause is specified.

Note:

The query optimizer treats all internal system tables as if theAUTO_UPDATE_STATISTICS setting is ON, regardless of the actualsetting. These tables include system base tables, xml indexes, full-

text indexes, service broker queue tables, and query notificationtables.

For more information, see Index Statistics.

AUTO_UPDATE_STATISTICS_ASYNC { ON | OFF }ON

Page 20: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 20/36

Queries that initiate an automatic update of out-of-datestatistics will not wait for the statistics to be updated beforecompiling. Subsequent queries will use the updated statisticswhen they are available.

OFF

Queries that initiate an automatic update of out-of-datestatistics, wait until the updated statistics can be used in thequery optimization plan.

Setting this option to ON has no effect unlessAUTO_UPDATE_STATISTICS is set to ON.

For more information, see Index Statistics.

<sql_option>::=

Controls the ANSI compliance options at the database level.

ANSI_NULL_DEFAULT { ON | OFF }

Determines the default value, NULL or NOT NULL, of a column,alias data type, or CLR user-defined type for which thenullability is not explicitly defined in CREATE TABLE or ALTERTABLE statements. Columns that are defined with constraints

follow constraint rules regardless of this setting.

ON

The default value is NULL.

OFF

The default value is NOT NULL.

Connection-level settings that are set by using the SETstatement override the default database-level setting for

ANSI_NULL_DEFAULT. By default, ODBC and OLE DB clientsissue a connection-level SET statement settingANSI_NULL_DEFAULT to ON for the session when connectingto an instance of SQL Server. For more information, see SETANSI_NULL_DFLT_ON (Transact-SQL).

Page 21: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 21/36

For ANSI compatibility, setting the database optionANSI_NULL_DEFAULT to ON changes the database default toNULL.

The status of this option can be determined by examining the

is_ansi_null_default_on column in the sys.databasescatalog view or the IsAnsiNullDefault property of theDATABASEPROPERTYEX function.

ANSI_NULLS { ON | OFF }ON

All comparisons to a null value evaluate to UNKNOWN.

OFF

Comparisons of non-UNICODE values to a null value evaluateto TRUE if both values are NULL.

Connection-level settings that are set by using the SETstatement override the default database setting forANSI_NULLS. By default, ODBC and OLE DB clients issue aconnection-level SET statement setting ANSI_NULLS to ON forthe session when connecting to an instance of SQL Server. Formore information, see SET ANSI_NULLS (Transact-SQL).

SET ANSI_NULLS also must be set to ON when you create ormake changes to indexes on computed columns or indexedviews.

The status of this option can be determined by examining theis_ansi_nulls_on column in the sys.databases catalog viewor the IsAnsiNullsEnabled property of theDATABASEPROPERTYEX function.

ANSI_PADDING { ON | OFF }

ONStrings are padded to the same length before conversion orinserting to a varchar or nvarchar data type.

Trailing blanks in character values inserted into varchar ornvarchar columns and trailing zeros in binary values inserted

Page 22: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 22/36

into varbinary columns are not trimmed. Values are notpadded to the length of the column.

OFF

Trailing blanks for varchar or nvarchar and zeros forvarbinary are trimmed.

When OFF is specified, this setting affects only the definition of new columns.

char(n) and binary(n) columns that allow for nulls arepadded to the length of the column when ANSI_PADDING isset to ON, but trailing blanks and zeros are trimmed whenANSI_PADDING is OFF. char(n) and binary(n) columns that

do not allow nulls are always padded to the length of thecolumn.

Connection-level settings that are set by using the SETstatement override the default database-level setting forANSI_PADDING. By default, ODBC and OLE DB clients issue aconnection-level SET statement setting ANSI_PADDING to ONfor the session when connecting to an instance of SQL Server.For more information, see SET ANSI_PADDING (Transact-SQL).

Important:

We recommend that ANSI_PADDING always be set to ON.ANSI_PADDING must be ON when you create or manipulate indexeson computed columns or indexed views.

The status of this option can be determined by examining theis_ansi_padding_on column in the sys.databases catalogview or the IsAnsiPaddingEnabled property of theDATABASEPROPERTYEX function.

ANSI_WARNINGS { ON | OFF }ON

Errors or warnings are issued when conditions such as divide-by-zero occur or null values appear in aggregate functions.

OFF

Page 23: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 23/36

No warnings are raised and null values are returned whenconditions such as divide-by-zero occur.

SET ANSI_WARNINGS must be set to ON when you create ormake changes to indexes on computed columns or indexed

views.

Connection-level settings that are set by using the SETstatement override the default database setting forANSI_WARNINGS. By default, ODBC and OLE DB clients issuea connection-level SET statement setting ANSI_WARNINGS toON for the session when connecting to an instance of SQLServer. For more information, see SET ANSI_WARNINGS(Transact-SQL).

The status of this option can be determined by examining theis_ansi_warnings_on column in the sys.databases catalogview or the IsAnsiWarningsEnabled property of theDATABASEPROPERTYEX function.

ARITHABORT { ON | OFF }ON

A query is ended when an overflow or divide-by-zero erroroccurs during query execution.

OFF

A warning message is displayed when one of these errorsoccurs, but the query, batch, or transaction continues toprocess as if no error occurred.

SET ARITHABORT must be set to ON when you create or makechanges to indexes on computed columns or indexed views.

The status of this option can be determined by examining the

is_arithabort_on column in the sys.databases catalog viewor the IsArithmeticAbortEnabled property of theDATABASEPROPERTYEX function.

CONCAT_NULL_YIELDS_NULL { ON | OFF }ON

Page 24: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 24/36

The result of a concatenation operation is NULL when eitheroperand is NULL. For example, concatenating the characterstring "This is" and NULL causes the value NULL, instead of thevalue "This is".

OFF

The null value is treated as an empty character string.

CONCAT_NULL_YIELDS_NULL must be set to ON when youcreate or make changes to indexes on computed columns orindexed views.

Connection-level settings that are set by using the SETstatement override the default database setting for

CONCAT_NULL_YIELDS_NULL. By default, ODBC and OLE DBclients issue a connection-level SET statement settingCONCAT_NULL_YIELDS_NULL to ON for the session whenconnecting to an instance of SQL Server. For moreinformation, see SET CONCAT_NULL_YIELDS_NULL (Transact-SQL).

The status of this option can be determined by examining theis_concat_null_yields_null_on column in thesys.databases catalog view or the IsNullConcat property of 

the DATABASEPROPERTYEX function.

QUOTED_IDENTIFIER { ON | OFF }ON

Double quotation marks can be used to enclose delimitedidentifiers.

All strings delimited by double quotation marks are interpretedas object identifiers. Quoted identifiers do not have to followthe Transact-SQL rules for identifiers. They can be keywords

and can include characters not generally allowed in Transact-SQL identifiers. If a single quotation mark (') is part of theliteral string, it can be represented by double quotation marks(").

OFF

Page 25: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 25/36

Identifiers cannot be in quotation marks and must follow allTransact-SQL rules for identifiers. Literals can be delimited byeither single or double quotation marks.

SQL Server also allows for identifiers to be delimited by square

brackets ([ ]). Bracketed identifiers can always be used,regardless of the setting of QUOTED_IDENTIFIER. For moreinformation, see Delimited Identifiers (Database Engine).

When a table is created, the QUOTED IDENTIFIER option isalways stored as ON in the metadata of the table, even if theoption is set to OFF when the table is created.

Connection-level settings that are set by using the SETstatement override the default database setting forQUOTED_IDENTIFIER. By default, ODBC and OLE DB clientsissue a connection-level SET statement settingQUOTED_IDENTIFIER to ON when connecting to an instance of SQL Server. For more information, see SETQUOTED_IDENTIFIER (Transact-SQL).

The status of this option can be determined by examining theis_quoted_identifier_on column in the sys.databasescatalog view or the IsQuotedIdentifiersEnabled property of 

the DATABASEPROPERTYEX function.

NUMERIC_ROUNDABORT { ON | OFF }ON

An error is generated when loss of precision occurs in anexpression.

OFF

Losses of precision do not generate error messages and theresult is rounded to the precision of the column or variable

storing the result.

NUMERIC_ROUNDABORT must be set to OFF when you createor make changes to indexes on computed columns or indexedviews.

Page 26: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 26/36

The status of this option can be determined by examining theis_numeric_roundabort_on column in the sys.databasescatalog view or the IsNumericRoundAbortEnabled propertyof the DATABASEPROPERTYEX function.

RECURSIVE_TRIGGERS { ON | OFF }ON

Recursive firing of AFTER triggers is allowed.

OFF

Only direct recursive firing of AFTER triggers is not allowed. Toalso disable indirect recursion of AFTER triggers, set the nestedtriggers server option to 0 by using sp_configure.

Note:Only direct recursion is prevented when RECURSIVE_TRIGGERS isset to OFF. To disable indirect recursion, you must also set thenested triggers server option to 0.

The status of this option can be determined by examining theis_recursive_triggers_on column in the sys.databasescatalog view or the IsRecursiveTriggersEnabled property of the DATABASEPROPERTYEX function.

<recovery_option> ::=

Controls database recovery options and disk I/O error checking.

FULL

Provides full recovery after media failure by using transactionlog backups. If a data file is damaged, media recovery canrestore all committed transactions. For more information, seeOverview of Full Recovery.

BULK_LOGGEDProvides recovery after media failure by combining the bestperformance and least amount of log-space use for certainlarge-scale or bulk operations. For information about whatoperations are bulk logged, see Minimally Logged Operations.Under the BULK_LOGGED recovery model, logging for these

Page 27: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 27/36

operations is minimal. For more information, see Overview of Bulk-Logged Recovery.

SIMPLE

A simple backup strategy that uses minimal log space isprovided. Log space can be automatically reused when it is nolonger required for server failure recovery. For moreinformation, see Overview of Simple Recovery.

Important:

The simple recovery model is easier to manage than the other twomodels but at the expense of greater data loss exposure if a datafile is damaged. All changes since the most recent database ordifferential database backup are lost and must be manually

reentered.

The default recovery model is determined by the recovery model of the model database. For more information about selecting theappropriate recovery model, see Choosing a Recovery Strategy ThatSupports Your Applications.

The status of this option can be determined by examining therecovery_model and recovery_model_desc columns in thesys.databases catalog view or the Recovery property of theDATABASEPROPERTYEX function.

TORN_PAGE_DETECTION { ON | OFF }ON

Incomplete pages can be detected by the Database Engine.

OFF

Incomplete pages cannot be detected by the Database Engine.

Important:The syntax structure TORN_PAGE_DETECTION ON | OFF will beremoved in a future version of Microsoft SQL Server. Avoid usingthis syntax structure in new development work, and plan to modifyapplications that currently use the syntax structure. Use thePAGE_VERIFY option instead.

PAGE_VERIFY { CHECKSUM | TORN_PAGE_DETECTION | NONE }

Page 28: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 28/36

Discovers damaged database pages caused by disk I/O patherrors. Disk I/O path errors can be the cause of databasecorruption problems and are generally caused by powerfailures or disk hardware failures that occur at the time the

page is being written to disk.CHECKSUM

Calculates a checksum over the contents of the whole pageand stores the value in the page header when a page is writtento disk. When the page is read from disk, the checksum isrecomputed and compared to the checksum value stored in thepage header. If the values do not match, error message 824(indicating a checksum failure) is reported to both the SQLServer error log and the Windows event log. A checksum

failure indicates an I/O path problem. To determine the rootcause requires investigation of the hardware, firmware drivers,BIOS, filter drivers (such as virus software), and other I/Opath components.

TORN_PAGE_DETECTION

Saves a specific bit for each 512-byte sector in the 8-kilobyte(KB) database page and stored in the database page headerwhen the page is written to disk. When the page is read from

disk, the torn bits stored in the page header are compared tothe actual page sector information. Unmatched values indicatethat only part of the page was written to disk. In this situation,error message 824 (indicating a torn page error) is reported toboth the SQL Server error log and the Windows event log. Tornpages are typically detected by database recovery if it is trulyan incomplete write of a page. However, other I/O pathfailures can cause a torn page at any time.

NONE

Database page writes will not generate a CHECKSUM orTORN_PAGE_DETECTION value. SQL Server will not verify achecksum or torn page during a read even if a CHECKSUM orTORN_PAGE_DETECTION value is present in the page header.

Consider the following important points when you use thePAGE_VERIFY option:

Page 29: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 29/36

• In SQL Server 2005, the default is CHECKSUM. Werecommend that you use CHECKSUM. In SQL Server 2000,TORN_PAGE_DETECTION is the default.

• TORN_PAGE_DETECTION may use fewer resources butprovides a minimal subset of the CHECKSUM protection.

• PAGE_VERIFY can be set without taking the databaseoffline, locking the database, or otherwise impedingconcurrency on that database.

• CHECKSUM is mutually exclusive toTORN_PAGE_DETECTION. Both options cannot be enabled atthe same time.

When a torn page or checksum failure is detected, you canrecover by restoring the data or potentially rebuilding theindex if the failure is limited only to index pages. If youencounter a checksum failure, to determine the type of database page or pages affected, run DBCC CHECKDB. Formore information about restore options, see DatabaseBackups. Although restoring the data will resolve the datacorruption problem, the root cause, for example, diskhardware failure, should be diagnosed and corrected as soon

as possible to prevent continuing errors.

SQL Server will retry any read that fails with a checksum, tornpage, or other I/O error four times. If the read is successful inany one of the retry attempts, a message will be written to theerror log and the command that triggered the read willcontinue. If the retry attempts fail, the command will fail witherror message 824.

For more information about checksum, torn page, read-retry,

error messages 823 and 824, and other SQL Server I/Oauditing features, see this Microsoft Web site.

DROP Database:

DROP DATABASE ARCHIVE

Change DBowner:

Page 30: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 30/36

sp_changedbowner [ @loginame = ] 'login'[ , [ @map= ] remap_alias_flag ]

Dettach & Attach:

sp_detach_db [ @dbname= ] 'dbname' [ , [ @skipchecks= ] 'skipchecks' ][ , [ @KeepFulltextIndexFile= ]

'KeepFulltextIndexFile' ]

sp_attach_db [ @dbname= ] 'dbname'  , [ @filename1= ] 'filename_n' [ ,...16 ]

(This Feature will be remove from the future versions).

System tables:

sys.database_files

sys.databases

sys.data_spaces

sys.filegroups

sys.master_files 

Database SnapShots:

This topic describes database snapshots, which are new in Microsoft

SQL Server 2005. Database snapshots are available only in theEnterprise Edition of Microsoft SQL Server 2005.

A database snapshot is a read-only, static view of a database (the

source database). Multiple snapshots can exist on a source database

and always reside on the same server instance as the database.

Each database snapshot is transactionally consistent with the source

Page 31: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 31/36

database as of the moment of the snapshot's creation. A snapshot

persists until it is explicitly dropped by the database owner.

Snapshots can be used for reporting purposes. Also, in the event of 

a user error on a source database, you can revert the sourcedatabase to the state it was in when the snapshot was created.

Data loss is confined to updates to the database since the

snapshot's creation.

How the sanp shots works:

Uses of Snapshots:

Limitations:

The database cannot be dropped, detached, or restored

Only EnterPrise Edition.

Performance is reduced, due to increased I/O on the source

database resulting from a copy-on-write operation to the snapshot

every time a page is updated.

Files cannot be dropped from the source database or from anysnapshots.

Full-text indexing is not supported on database snapshots, and full-text catalogs are not propagated from the source database.

Creation Of snapshot:

CREATE DATABASE Archive_dbss1800 ON

( NAME = Archive_Data, FILENAME = 'G:\MSSQL\Data\Archive_Data_data_1800.ss' )AS SNAPSHOT OF Archive;GO

Create Database TestSnapshot_05282008ON(Name = 'TestSnapshot_System',Filename ='G:\MSSQL.4\MSSQL\Data\TestSnapshot_System.ss'),

Page 32: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 32/36

(Name = 'TestSnapshot_data',Filename ='G:\MSSQL.4\MSSQL\Data\TestSnapshot_data.ss'),(Name = 'TestSnapshot_Index',Filename ='G:\MSSQL.4\MSSQL\Data\TestSnapshot_Index.ss')AS SNAPSHOT OF TestSnapshot

DROP DATABASE Archive_dbss1800

Select the size column from either sys.database_files in thedatabase snapshot or from sys.master_files. The size column insys.database_files or sys.master_files reflects the maximumspace, in SQL pages, that the snapshot can ever use; this value isequivalent to the Windows Size field, except that it is represented

in terms of the number of SQL pages in the file; the size in bytes is:

( number_of_pages * 8192)

Reverting Database Snapshot:

RESTORE DATABASE Archive fromDATABASE_SNAPSHOT = ' Archive_dbss1800';

USE master;RESTORE DATABASE TestSnapshot FROM DATABASE_SNAPSHOT ='TestSnapshot_05282008';

Restrictions on Reverting

You cannot revert to a snapshot if:

• The source database contains any read-only or compressedfilegroups.

• Any filegroups are offline that were online when the snapshotwas created.

Page 33: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 33/36

• More than one snapshot of the database exists at the time of reverting.

Before reverting a database, consider the following:

• Reverting from a database snapshot is not intended for mediarecovery. Unlike a regular backup set, the database snapshot isan incomplete copy of the database files. If either the database orthe database snapshot is corrupted, reverting from a snapshot isunlikely to correct the problem.

• During a revert operation, both the snapshot and the sourcedatabase are unavailable. The source database and snapshot areboth marked "In restore." If an error occurs during the revert

operation, when the database starts up again, the revertoperation will try to finish reverting.

• Because a successful revert operation automatically rebuildsthe log, Microsoft recommends that you back up the log beforereverting a database. Although you cannot restore the original logto roll forward the database, the information in the original logfile can be useful for reconstructing lost data.

• Reverting breaks the log backup chain. Therefore, before you

can take log backups of the reverted database, you must firsttake a full database backup or file backup. Microsoft recommendsa full database backup.

Shrink Database:

exec CTIRPTS.dbo.sp_spaceused

DBCC SHRINKDATABASE( 'database_name' | database_id | 0

[ ,target_percent ][ , { NOTRUNCATE | TRUNCATEONLY } ])[ WITH NO_INFOMSGS ]

'database_name' | database_id | 0

Page 34: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 34/36

Is the name or ID of the database to be shrunk. If 0 isspecified, the current database is used. Database names mustcomply with the rules for identifiers.

target_percent  

Is the percentage of free space that you want left in thedatabase file after the database has been shrunk.

NOTRUNCATE

Causes the freed file space to be retained in the database files.If not specified, the freed file space is released to theoperating system.

TRUNCATEONLY

Causes any unused space in the data files to be released to theoperating system and shrinks the file to the last allocatedextent, reducing the file size without moving any data. Noattempt is made to relocate rows to unallocated pages.target_percent is ignored when TRUNCATEONLY is used.

WITH NO_INFOMSGS

Suppresses all informational messages that have severitylevels from 0 through 10.

DBCC SHRINKFILE(

{ 'file_name' | file_id }{ [ , EMPTYFILE ]| [ [ , target_size ] [ , { NOTRUNCATE | TRUNCATEONLY

} ] ]}

)[ WITH NO_INFOMSGS ]

Empty File: Migrates all data from the specified file to other files in

the same filegroup. The SQL Server 2005 Database Engine does notallow for data to be placed on the file used with the EMPTYFILE

Page 35: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 35/36

option. This option enables the file to be dropped by using ALTERDATABASE

file_name' 

Is the logical name of the file to be shrunk. File names mustcomply with the rules for identifiers.

file_id 

Is the identification (ID) number of the file to be shrunk. Toobtain a file ID, use the FILE_ID function or searchsys.database_files in the current database.

target_size

Is the size for the file in megabytes, expressed as an integer.If not specified, DBCC SHRINKFILE reduces the size to thedefault file size.

If target_size is specified, DBCC SHRINKFILE tries to shrinkthe file to the specified size. Used pages in the part of the fileto be freed are relocated to available free space in the part of the file retained. For example, if there is a 10-MB data file, aDBCC SHRINKFILE with a target_size of 8 causes all usedpages in the last 2 MB of the file to be reallocated into any

available free slots in the first 8 MB of the file. DBCCSHRINKFILE does not shrink a file past the size needed tostore the data in the file. For example, if 7 MB of a 10-MB datafile is used, a DBCC SHRINKFILE statement with a target_sizeof 6 shrinks the file to only 7 MB, not 6 MB.

EMPTYFILE

Migrates all data from the specified file to other files in thesame filegroup. The SQL Server 2005 Database Engine does

not allow for data to be placed on the file used with theEMPTYFILE option. This option enables the file to be droppedby using ALTER DATABASE.

NOTRUNCATE

Causes the freed file space to be retained in the files.

Page 36: 03 27 2008 Create Database

8/4/2019 03 27 2008 Create Database

http://slidepdf.com/reader/full/03-27-2008-create-database 36/36

When NOTRUNCATE is specified with target_size, the spacefreed is not released to the operating system. The only effectis to relocate used pages from before the target_size line tothe front of the file. When NOTRUNCATE is not specified, all

freed file space is returned to the operating system.TRUNCATEONLY

Causes any unused space in the files to be released to theoperating system and shrinks the file to the last allocatedextent, reducing the file size without moving any data. Noattempt is made to relocate rows to unallocated pages.target_size is ignored when TRUNCATEONLY is used.

WITH

Enables options to be specified.

NO_INFOMSGS

Suppresses all informational messages.