SQL 2014 - Move Database Files
SQL 2014 - Move Database Files
Database Files
This document is provided "as‐is". Information and views expressed in this document, including URL
and other Internet Web site references, may change without notice. This document does not provide
you with any legal rights to any intellectual property in any Microsoft product or product name. You
may copy and use this document for your internal, reference purposes. You may modify this document
may copy and use this document for your internal, reference purposes. You may modify this document
for your internal, reference purposes.© 2016 Microsoft. All rights reserved. Terms of Use
﴾https://msdn.microsoft.com/cc300389.aspx﴿ | Trademarks
﴾http://www.microsoft.com/library/toolbar/3.0/trademarks/en‐us.mspx﴿
Table Of Contents
Move Database Files
See Also
In SQL Server, you can move system and user databases by specifying the new file location in the
FILENAME clause of the ALTER DATABASE statement. Data, log, and full‐text catalog files can be
moved in this way. This may be useful in the following situations:
Failure recovery. For example, the database is in suspect mode or has shut down, because
of a hardware failure.
Planned relocation.
In This Section
Topic Description
Move User Describes the procedures for moving user database files and full‐text
Databases catalog files to a new location.
Move System Describes the procedures for moving system database files to a new
Databases location.
See Also
ALTER DATABASE ﴾Transact‐SQL﴿
CREATE DATABASE ﴾SQL Server Transact‐SQL﴿
Database Detach and Attach ﴾SQL Server﴿
© 2016 Microsoft
See Also
ALTER DATABASE ﴾Transact‐SQL﴿
Modifies a database, or the files and filegroups associated with the database. Adds or removes files
and filegroups from a database, changes the attributes of a database or its files and filegroups,
changes the database collation, and sets database options. Database snapshots cannot be
modified. To modify database options associated with replication, use sp_replicationdboption.
Applies to: SQL Server ﴾SQL Server 2008 through current version﴿, Azure SQL Database.
Because of its length, the ALTER DATABASE syntax is separated into the following topics:
ALTER DATABASE
The current topic provides the syntax for changing the name and the collation of a
database.
Syntax
‐‐ SQL Server Syntax
ALTER DATABASE { database_name | CURRENT }
{
MODIFY NAME = new_database_name
| COLLATE collation_name
| <file_and_filegroup_options>
| <set_database_options>
}
[;]
<file_and_filegroup_options >::=
<add_or_modify_files>::=
<filespec>::=
<add_or_modify_filegroups>::=
<filegroup_updatability_option>::=
<set_database_options>::=
<optionspec>::=
<auto_option> ::=
<change_tracking_option> ::=
<cursor_option> ::=
<database_mirroring_option> ::=
<date_correlation_optimization_option> ::=
<db_encryption_option> ::=
<db_state_option> ::=
<db_update_option> ::=
<db_user_access_option> ::=
<delayed_durability_option> ::= <external_access_option> ::=
<FILESTREAM_options> ::=
<HADR_options> ::=
<parameterization_option> ::=
<recovery_option> ::=
<service_broker_option> ::=
<snapshot_option> ::=
<sql_option> ::=
<termination> ::=
‐‐ Azure SQL Database Syntax
ALTER DATABASE database_name
{
MODIFY NAME =new_database_name
| MODIFY ( <edition_options> [, ... n] )
| COLLATE collation_name
| SET { <set_database_options> }
}
<edition_options> ::=
{
MAXSIZE = { 100 MB | 500 MB |1 | 5 | 10 | 20 | 30 … 150 … 500 } GB
| EDITION = { 'web' | 'business' | 'basic' | 'standard' | 'Premium' }
| SERVICE_OBJECTIVE = { 'shared' | 'basic' | 'S0' | 'S1' | 'S2' | 'P1' | 'P2' | 'P
}
<set_database_options> ::=
<db_update_option>
<db_update_option> ::=
{ READ_ONLY | READ_WRITE }
[;]
Arguments
database_name
Is the name of the database to be modified.
Note
CURRENT
COLLATE collation_name
Applies to: SQL Server 2008 through SQL Server 2014, SQL Database Update
﴾preview﴿.
Specifies the collation for the database. collation_name can be either a Windows collation
name or a SQL collation name. If not specified, the database is assigned the collation of
the instance of SQL Server.
When creating databases with other than the default collation, the data in the database
always respects the specified collation. For SQL Server, when creating a contained
database, the internal catalog information is maintained using the SQL Server default
collation, Latin1_General_100_CI_AS_WS_KS_SC. For SQL Database, internal catalog
information is maintained using SQL_Latin1_General_CP1_CI_AS.
For more information about the Windows and SQL collation names, see COLLATE
﴾Transact‐SQL﴿.
MODIFY ﴾MAXSIZE = [100 MB | 500 MB | 1 | 5 | 10 | 20 | 30 … 150…500] GB﴿
Applies to: Azure SQL Database. Web and Business editions are not supported by
SQL Database Update ﴾preview﴿.
Specifies the maximum size of the database. The maximum size must comply with the
valid set of values for the EDITION property of the database. Changing the maximum size
of the database may cause the database EDITION to be changed. Following table lists the
supported MAXSIZE values and the defaults ﴾D﴿ for the SQL Database service tiers.
100 MB √ √ √ √
500 MB √ √ √
1 GB √ ﴾D﴿ √ √ √
2 GB √ ﴾D﴿ √ √
5 GB √ √ √
10 GB √ ﴾D﴿ √ √
20 GB √ √ √
30 GB √ √ √
40 GB √ √ √
50 GB √ √ √
100 GB √ √ √
150 GB √ √ √
200 GB √ √
250 GB √ ﴾D﴿ √
300 GB √
400 GB √
500 GB √ ﴾D﴿
If MAXSIZE is set to less than 5 GB, and EDITION is not specified, the database
edition will automatically be set to Web.
If MAXSIZE is set to greater than 5 GB, and EDITION is not specified, the database
edition will automatically be set to Business.
If EDITION is specified but MAXSIZE is not specified, the default value for the
edition is used. For example, is the EDITION is set to Standard, and the MAXSIZE is
not specified, then the MAXSIZE is automatically set to 500 MB.
If neither MAXSIZE nor EDITION is specified, the EDITION is set to Web, and
MAXSIZE is set to 1 GB.
Applies to: Azure SQL Database. Web and Business editions are not supported by
SQL Database Update ﴾preview﴿.
Changes the edition of the database. SQL Database service tiers can be set or modified
using the EDITION parameter. EDITION change will fail if the MAXSIZE property for the
database is set to a value outside the valid range supported by that edition.
Important
Business and Web service tiers will be retired September 2015. For more information,
see Web and Business FAQ.
SERVICE_OBJECTIVE
Specifies the performance level. For service objective descriptions and more information
about the size, editions, and the service objectives combinations, see Azure SQL
Database Service Tiers and Performance Levels. If the specified SERVICE_OBJECTIVE is not
supported by the EDITION you receive an error. To change the SERVICE_OBJECTIVE value
from one tier to another ﴾for example from S1 to P1﴿, you must also change the EDITION
value.
<db_update_option> ::=
{ READ_ONLY | READ_WRITE }
READ_ONLY
Users can read data from the database but not modify it.
READ_WRITE
The database is available for read and write operations.
Note
<delayed_durability_option> ::=
For more information see ALTER DATABASE SET Options ﴾Transact‐SQL﴿ and Control Transaction
Durability.
<file_and_filegroup_options>::=
For more information, see ALTER DATABASE File and Filegroup Options ﴾Transact‐SQL﴿.
<set_database_options>::=
For more information, see ALTER DATABASE SET Options ﴾Transact‐SQL﴿, ALTER DATABASE
Database Mirroring ﴾Transact‐SQL﴿, ALTER DATABASE SET HADR ﴾Transact‐SQL﴿, and ALTER
DATABASE Compatibility Level ﴾Transact‐SQL﴿.
Remarks
To remove a database, use DROP DATABASE.
The ALTER DATABASE statement must run in autocommit mode ﴾the default transaction
management mode﴿ and is not allowed in an explicit or implicit transaction.
The state of a database file ﴾for example, online or offline﴿, is maintained independently from
the state of the database. For more information, see File States. The state of the files within a
filegroup determines the availability of the whole filegroup. For a filegroup to be available, all
files within the filegroup must be online. If a filegroup is offline, any try to access the filegroup
by an SQL statement will fail with an error. When you build query plans for SELECT statements,
the query optimizer avoids nonclustered indexes and indexed views that reside in offline
filegroups. This enables these statements to succeed. However, if the offline filegroup contains
the heap or clustered index of the target table, the SELECT statements fail. Additionally, any
INSERT, UPDATE, or DELETE statement that modifies a table with any index in an offline
filegroup will fail.
When a database is in the RESTORING state, most ALTER DATABASE statements will fail. The
exception is setting database mirroring options. A database may be in the RESTORING state
during an active restore operation or when a restore operation of a database or log file fails
because of a corrupted backup file.
The plan cache for the instance of SQL Server is cleared by setting one of the following options.
OFFLINE READ_WRITE
READ_ONLY PAGE_VERIFY
Clearing the plan cache causes a recompilation of all subsequent execution plans and can cause
a sudden, temporary decrease in query performance. For each cleared cachestore in the plan
cache, the SQL Server error log contains the following informational message: "SQL Server has
encountered %d occurrence﴾s﴿ of cachestore flush for the '%s' cachestore ﴾part of plan cache﴿
due to some database maintenance or reconfigure operations". This message is logged every
five minutes as long as the cache is flushed within that time interval.
A database has the AUTO_CLOSE database option set to ON. When no user connection
references or uses the database, the background task tries to close and shut down the
database automatically.
You run several queries against a database that has default options. Then, the database is
dropped.
If the following objects, which depend on the database collation, exist in the database,
the ALTER DATABASEdatabase_nameCOLLATE statement will fail. SQL Server will return
an error message for each object blocking the ALTER action:
User‐defined functions and views created with SCHEMABINDING.
Computed columns.
CHECK constraints.
Table‐valued functions that return tables with character columns with collations
inherited from the default database collation.
Changing the database collation does not create duplicates among any system names for the
database objects. If duplicate names result from the changed collation, the following
namespaces may cause the failure of a database collation change:
Schema names.
Duplicate names resulting from the new collation will cause the change action to fail, and SQL
Server will return an error message specifying the namespace where the duplicate was found.
Permissions
SQL Server
Requires ALTER permission on the database.
Security Note
The owner of the database cannot alter the database unless they are a member of the
dbmanager role.
Examples
USE master;
GO
ALTER DATABASE AdventureWorks2012
Modify Name = Northwind ;
GO
USE master;
GO
CREATE DATABASE testdb
COLLATE SQL_Latin1_General_CP1_CI_AS ;
GO
ALTER DATABASE testDB
COLLATE French_CI_AI ;
GO
See Also
Reference
CREATE DATABASE ﴾SQL Server Transact‐SQL﴿
DATABASEPROPERTYEX ﴾Transact‐SQL﴿
DROP DATABASE ﴾Transact‐SQL﴿
SET TRANSACTION ISOLATION LEVEL ﴾Transact‐SQL﴿
EVENTDATA ﴾Transact‐SQL﴿
sp_configure ﴾Transact‐SQL﴿
sp_spaceused ﴾Transact‐SQL﴿
sys.databases ﴾Transact‐SQL﴿
sys.database_files ﴾Transact‐SQL﴿
sys.database_mirroring_witnesses ﴾Transact‐SQL﴿
sys.data_spaces ﴾Transact‐SQL﴿
sys.filegroups ﴾Transact‐SQL﴿
sys.master_files ﴾Transact‐SQL﴿
Concepts
System Databases
© 2016 Microsoft
Creates a new database and the files used to store the database, a database snapshot, or attaches
a database from the detached files of a previously created database.
Applies to: SQL Server ﴾SQL Server 2008 through current version﴿. For syntax related to SQL
Database, see CREATE DATABASE ﴾Azure SQL Database﴿.
Syntax
Create a database
CREATE DATABASE database_name
[ CONTAINMENT = { NONE | PARTIAL } ]
[ ON
[ PRIMARY ] <filespec> [ ,...n ]
[ , <filegroup> [ ,...n ] ]
[ LOG ON <filespec> [ ,...n ] ]
]
[ COLLATE collation_name ]
[ WITH <option> [,...n ] ]
[;]
<option> ::=
{
FILESTREAM ( <filestream_option> [,...n ] )
| DEFAULT_FULLTEXT_LANGUAGE = { lcid | language_name | language_alias }
| DEFAULT_LANGUAGE = { lcid | language_name | language_alias }
| NESTED_TRIGGERS = { OFF | ON }
| TRANSFORM_NOISE_WORDS = { OFF | ON}
| TWO_DIGIT_YEAR_CUTOFF = <two_digit_year_cutoff>
| DB_CHAINING { OFF | ON }
| TRUSTWORTHY { OFF | ON }
}
<filestream_option> ::=
{
NON_TRANSACTED_ACCESS = { OFF | READ_ONLY | FULL }
| DIRECTORY_NAME = 'directory_name'
}
<filespec> ::=
{
(
NAME = logical_file_name ,
FILENAME = { 'os_file_name' | 'filestream_path' }
[ , SIZE = size [ KB | MB | GB | TB ] ]
[ , MAXSIZE = { max_size [ KB | MB | GB | TB ] | UNLIMITED } ]
[ , FILEGROWTH = growth_increment [ KB | MB | GB | TB | % ] ]
)
}
<filegroup> ::=
{
FILEGROUP filegroup name [ [ CONTAINS FILESTREAM ] [ DEFAULT ] | CONTAINS MEMORY_OPTIM
<filespec> [ ,...n ]
}
<service_broker_option> ::=
{
ENABLE_BROKER
| NEW_BROKER
| ERROR_BROKER_CONVERSATIONS
}
Attach a database
CREATE DATABASE database_name
ON <filespec> [ ,...n ]
FOR { { ATTACH [ WITH <attach_database_option> [ , ...n ] ] }
| ATTACH_REBUILD_LOG }
[;]
<attach_database_option> ::=
{
<service_broker_option>
| RESTRICTED_USER
| FILESTREAM ( DIRECTORY_NAME = { 'directory_name' | NULL } )
}
Create a database snapshot
CREATE DATABASE database_snapshot_name
ON
(
NAME = logical_file_name,
FILENAME = 'os_file_name'
) [ ,...n ]
AS SNAPSHOT OF source_database_name
[;]
Arguments
database_name
Is the name of the new database. Database names must be unique within an instance of
SQL Server and comply with the rules for identifiers.
If data file name is not specified, SQL Server uses database_name as both the
logical_file_name and as the os_file_name. The default path is obtained from the registry.
The default path can be changed by using the Server Properties ﴾Database Settings
Page﴿ in Management Studio. Changing the default path requires restarting SQL Server.
ON
Specifies that the disk files used to store the data sections of the database, data files, are
explicitly defined. ON is required when followed by a comma‐separated list of <filespec>
items that define the data files for the primary filegroup. The list of files in the primary
filegroup can be followed by an optional, comma‐separated list of <filegroup> items
that define user filegroups and their files.
PRIMARY
Specifies that the associated <filespec> list defines the primary file. The first file specified
in the <filespec> entry in the primary filegroup becomes the primary file. A database can
have only one primary file. For more information, see Database Files and Filegroups.
If PRIMARY is not specified, the first file listed in the CREATE DATABASE statement
becomes the primary file.
LOG ON
Specifies that the disk files used to store the database log, log files, are explicitly defined.
LOG ON is followed by a comma‐separated list of <filespec> items that define the log
files. If LOG ON is not specified, one log file is automatically created, which has a size that
is 25 percent of the sum of the sizes of all the data files for the database, or 512 KB,
whichever is larger. This file is placed in the default log‐file location. For information
about this location, see View or Change the Default Locations for Data and Log Files ﴾SQL
Server Management Studio﴿.
COLLATE collation_name
Specifies the default collation for the database. Collation name can be either a Windows
collation name or a SQL collation name. If not specified, the database is assigned the
default collation of the instance of SQL Server. A collation name cannot be specified on a
database snapshot.
For more information about the Windows and SQL collation names, see COLLATE
﴾Transact‐SQL﴿.
Note
WITH <option>
<filestream_options>
Value Description
DIRECTORY_NAME = <directory_name>
The following options are allowable only when CONTAINMENT has been set to PARTIAL.
If CONTAINMENT is set to NONE, errors will occur.
See Configure the default full‐text language Server Configuration Option for a full
description of this option.
See Configure the default language Server Configuration Option for a full
description of this option.
See Configure the nested triggers Server Configuration Option for a full
description of this option.
See transform noise words Server Configuration Optionfor a full description of this
option.
Four digits representing a year. 2049 is the default value. See Configure the two
digit year cutoff Server Configuration Option for a full description of this option.
DB_CHAINING { OFF | ON }
Important
The instance of SQL Server will recognize this setting when the cross db
ownership chaining server option is 0 ﴾OFF﴿. When cross db ownership
chaining is 1 ﴾ON﴿, all user databases can participate in cross‐database
ownership chains, regardless of the value of this option. This option is set by
using sp_configure.
To set this option, requires membership in the sysadmin fixed server role. The
DB_CHAINING option cannot be set on these system databases: master, model,
tempdb.
TRUSTWORTHY { OFF | ON }
By default, all system databases except the msdb database have TRUSTWORTHY
set to OFF. The value cannot be changed for the model and tempdb databases.
We recommend that you never set the TRUSTWORTHY option to ON for the
master database.
To set this option, requires membership in the sysadmin fixed server role.
If a read/write database has a single log file that is currently unavailable, and if the
database was shut down with no users or open transactions before the attach operation,
FOR ATTACH automatically rebuilds the log file and updates the primary file. In contrast,
for a read‐only database, the log cannot be rebuilt because the primary file cannot be
updated. Therefore, when you attach a read‐only database with a log that is unavailable,
you must provide the log files, or the files in the FOR ATTACH clause.
Note
In SQL Server, any full‐text files that are part of the database that is being attached will
be attached with the database. To specify a new path of the full‐text catalog, specify the
new location without the full‐text operating system file name. For more information, see
the Examples section.
Attaching a database that contains a FILESTREAM option of "Directory name", into a SQL
Server instance will prompt SQL Server to verify that the Database_Directory name is
unique. If it is not, the attach operation fails with the error, "FILESTREAM
Database_Directory name <name> is not unique in this SQL Server instance". To avoid
this error, the optional parameter, directory_name, should be passed in to this operation.
FOR ATTACH can specify the RESTRICTED_USER option. RESTRICTED_USER allows for
only members of the db_owner fixed database role and dbcreator and sysadmin fixed
server roles to connect to the database, but does not limit their number. Attempts by
unqualified users are refused.
If the database uses Service Broker, use the WITH <service_broker_option> in your FOR
ATTACH clause:
<service_broker_option>
Controls Service Broker message delivery and the Service Broker identifier for the
database. Service Broker options can only be specified when the FOR ATTACH
clause is used.
ENABLE_BROKER
Specifies that Service Broker is enabled for the specified database. That is,
message delivery is started, and is_broker_enabled is set to true in the
sys.databases catalog view. The database retains the existing Service Broker
identifier.
NEW_BROKER
Creates a new service_broker_guid value in both sys.databases and the
restored database and ends all conversation endpoints with clean up. The
broker is enabled, but no message is sent to the remote conversation
endpoints. Any route that references the old Service Broker identifier must
be re‐created with the new identifier.
ERROR_BROKER_CONVERSATIONS
Ends all conversations with an error stating that the database is attached or
restored. The broker is disabled until this operation is completed and then
enabled. The database retains the existing Service Broker identifier.
When you attach a replicated database that was copied instead of being detached,
consider the following:
If you attach the database to the same server instance and version as the original
database, no additional steps are required.
If you attach the database to the same server instance but with an upgraded
version, you must execute sp_vupgrade_replication to upgrade replication after
the attach operation is complete.
If you attach the database to a different server instance, regardless of version, you
must execute sp_removedbreplication to remove replication after the attach
operation is complete.
Note
Attach works with the vardecimal storage format, but the SQL Server Database
Engine must be upgraded to at least SQL Server 2005 Service Pack 2. You cannot
attach a database using vardecimal storage format to an earlier version of SQL Server.
For more information about the vardecimal storage format, see Data Compression.
When a database is first attached or restored to a new instance of SQL Server, a copy of
the database master key ﴾encrypted by the service master key﴿ is not yet stored in the
server. You must use the OPEN MASTER KEY statement to decrypt the database master
key ﴾DMK﴿. Once the DMK has been decrypted, you have the option of enabling
automatic decryption in the future by using the ALTER MASTER KEY REGENERATE
statement to provision the server with a copy of the DMK, encrypted with the service
master key ﴾SMK﴿. When a database has been upgraded from an earlier version, the DMK
should be regenerated to use the newer AES algorithm. For more information about
regenerating the DMK, see ALTER MASTER KEY ﴾Transact‐SQL﴿. The time required to
regenerate the DMK key to upgrade to AES depends upon the number of objects
protected by the DMK. Regenerating the DMK key to upgrade to AES is only necessary
once, and has no impact on future regenerations as part of a key rotation strategy. For
information about how to upgrade a database by using attach, see Upgrade a Database
Using Detach and Attach ﴾Transact‐SQL﴿.
Security Note We recommend that you do not attach databases from unknown or
untrusted sources. Such databases could contain malicious code that might execute
unintended Transact‐SQL code or cause errors by modifying the schema or the physical
database structure. Before you use a database from an unknown or untrusted source, run
DBCC CHECKDB on the database on a nonproduction server, and also examine the code,
such as stored procedures or other user‐defined code, in the database.
Note
FOR ATTACH_REBUILD_LOG
Specifies that the database is created by attaching an existing set of operating system
files. This option is limited to read/write databases. There must be a <filespec> entry
specifying the primary file. If one or more transaction log files are missing, the log file is
rebuilt. The ATTACH_REBUILD_LOG automatically creates a new, 1 MB log file. This file is
placed in the default log‐file location. For information about this location, see View or
Change the Default Locations for Data and Log Files ﴾SQL Server Management Studio﴿.
Note
If the log files are available, the Database Engine uses those files instead of rebuilding
the log files.
Important
This operation breaks the log backup chain. We recommend that a full database
backup be performed after the operation is completed. For more information, see
BACKUP ﴾Transact‐SQL﴿.
Typically, FOR ATTACH_REBUILD_LOG is used when you copy a read/write database with
a large log to another server where the copy will be used mostly, or only, for read
operations, and therefore requires less log space than the original database.
For more information about attaching and detaching databases, see Database Detach
and Attach ﴾SQL Server﴿.
<filespec>
Controls the file properties.
NAME logical_file_name
Specifies the logical name for the file. NAME is required when FILENAME is specified,
except when specifying one of the FOR ATTACH clauses. A FILESTREAM filegroup cannot
be named PRIMARY.
logical_file_name
Is the logical name used in SQL Server when referencing the file. Logical_file_name
must be unique in the database and comply with the rules for identifiers. The
name can be a character or Unicode constant, or a regular or delimited identifier.
SIZE, MAXSIZE, and FILEGROWTH parameters can be set when a UNC path is
specified for the file.
If the file is on a raw partition, os_file_name must specify only the drive letter of an
existing raw partition. Only one data file can be created on each raw partition.
Data files should not be put on compressed file systems unless the files are read‐
only secondary files, or the database is read‐only. Log files should never be put on
compressed file systems.
The filegroup and file ﴾<filespec>﴿ must be created in the same statement.
SIZE size
Specifies the size of the file.
SIZE cannot be specified when the os_file_name is specified as a UNC path. SIZE does not
apply to a FILESTREAM filegroup.
size
Is the initial size of the file.
When size is not supplied for the primary file, the Database Engine uses the size of
the primary file in the model database. When a secondary data file or log file is
specified, but size is not specified for the file, the Database Engine makes the file 1
MB. The size specified for the primary file must be at least as large as the primary
file of the model database.
The kilobyte ﴾KB﴿, megabyte ﴾MB﴿, gigabyte ﴾GB﴿, or terabyte ﴾TB﴿ suffixes can be
used. The default is MB. Specify a whole number; do not include a decimal. Size is
an integer value. For values greater than 2147483647, use larger units.
MAXSIZE max_size
Specifies the maximum size to which the file can grow. MAXSIZE cannot be specified
when the os_file_name is specified as a UNC path.
max_size
Is the maximum file size. The KB, MB, GB, and TB suffixes can be used. The default
is MB. Specify a whole number; do not include a decimal. If max_size is not
specified, the file grows until the disk is full. Max_size is an integer value. For
values greater than 2147483647, use larger units.
UNLIMITED
Specifies that the file grows until the disk is full. In SQL Server, a log file specified with
unlimited growth has a maximum size of 2 TB, and a data file has a maximum size of 16
TB.
Note
There is no maximum size when this option is specified for a FILESTREAM container. It
continues to grow until the disk is full.
FILEGROWTH growth_increment
Specifies the automatic growth increment of the file. The FILEGROWTH setting for a file
cannot exceed the MAXSIZE setting. FILEGROWTH cannot be specified when the
os_file_name is specified as a UNC path. FILEGROWTH does not apply to a FILESTREAM
filegroup.
growth_increment
Is the amount of space added to the file every time new space is required.
The value can be specified in MB, KB, GB, TB, or percent ﴾%﴿. If a number is
specified without an MB, KB, or % suffix, the default is MB. When % is specified,
the growth increment size is the specified percentage of the size of the file at the
time the increment occurs. The size specified is rounded to the nearest 64 KB.
If FILEGROWTH is not specified, the default value is 1 MB for data files and 10%
for log files, and the minimum value is 64 KB.
Note
In SQL Server, the default growth increment for data files has changed from
10% to 1 MB. The log file default of 10% remains unchanged.
<filegroup>
Controls the filegroup properties. Filegroup cannot be specified on a database snapshot.
FILEGROUP filegroup_name
Is the logical name of the filegroup.
filegroup_name
filegroup_name must be unique in the database and cannot be the system‐
provided names PRIMARY and PRIMARY_LOG. The name can be a character or
Unicode constant, or a regular or delimited identifier. The name must comply with
the rules for identifiers.
CONTAINS FILESTREAM
Specifies that the filegroup stores FILESTREAM binary large objects ﴾BLOBs﴿ in the
file system.
CONTAINS MEMORY_OPTIMIZED_DATA
Specifies that the filegroup stores memory_optimized data in the file system. For
more information, see In‐Memory OLTP ﴾In‐Memory Optimization﴿. Only one
MEMORY_OPTIMIZED_DATA filegroup is allowed per database. For code samples
that create a filegroup to store memory‐optimized data, see Creating a Memory‐
Optimized Table and a Natively Compiled Stored Procedure.
DEFAULT
Specifies the named filegroup is the default filegroup in the database.
database_snapshot_name
Is the name of the new database snapshot. Database snapshot names must be unique
within an instance of SQL Server and comply with the rules for identifiers.
database_snapshot_name can be a maximum of 128 characters.
For descriptions of NAME and FILENAME and their values see the descriptions of the
equivalent <filespec> values.
Note
When you create a database snapshot, the other <filespec> options and the keyword
PRIMARY are disallowed.
AS SNAPSHOT OF source_database_name
Specifies that the database being created is a database snapshot of the source database
specified by source_database_name. The snapshot and source database must be on the
same instance.
Remarks
The master database should be backed up whenever a user database is created, modified, or
dropped.
The CREATE DATABASE statement must run in autocommit mode ﴾the default transaction
management mode﴿ and is not allowed in an explicit or implicit transaction.
You can use one CREATE DATABASE statement to create a database and the files that store the
database. SQL Server implements the CREATE DATABASE statement by using the following
steps:
1. The SQL Server uses a copy of the model database to initialize the database and its
metadata.
3. The Database Engine then fills the rest of the database with empty pages, except for
pages that have internal data that records how the space is used in the database.
A maximum of 32,767 databases can be specified on an instance of SQL Server.
Each database has an owner that can perform special activities in the database. The owner is the
user that creates the database. The database owner can be changed by using
sp_changedbowner.
When you create a database, make the data files as large as possible based on the maximum
amount of data you expect in the database
We recommend that you use a Storage Area Network ﴾SAN﴿, iSCSI‐based network, or locally
attached disk for the storage of your SQL Server database files, because this configuration
optimizes SQL Server performance and reliability.
Database Snapshots
You can use the CREATE DATABASE statement to create a read‐only, static view, a database
snapshot of the source database. A database snapshot is transactionally consistent with the
source database as it existed at the time when the snapshot was created. A source database can
have multiple snapshots.
Note
When you create a database snapshot, the CREATE DATABASE statement cannot reference
log files, offline files, restoring files, and defunct files.
If creating a database snapshot fails, the snapshot becomes suspect and must be deleted. For
more information, see DROP DATABASE ﴾Transact‐SQL﴿.
Database Options
Several database options are automatically set whenever you create a database. For a list of
these options, see ALTER DATABASE SET Options ﴾Transact‐SQL﴿.
Unless FOR ATTACH is specified, each new database inherits the database option settings from
the model database. For example, the database option auto shrink is set to true in model and in
any new databases you create. If you change the options in the model database, these new
option settings are used in any new databases you create. Changing operations in the model
database does not affect existing databases. If FOR ATTACH is specified on the CREATE
DATABASE statement, the new database inherits the database option settings of the original
database.
Permissions
Requires CREATE DATABASE, CREATE ANY DATABASE, or ALTER ANY DATABASE permission.
To maintain control over disk use on an instance of SQL Server, permission to create databases
is typically limited to a few login accounts.
The following example provides the permission to create a database to the database user Fay.
USE master;
GO
GRANT CREATE DATABASE TO [Fay];
GO
Attached Backed up
Detached Restored
The permissions prevent the files from being accidentally tampered with if they reside in a
directory that has open permissions.
Note
Microsoft SQL Server 2005 Express Edition does not set data and log file permissions.
Examples
USE master;
GO
CREATE DATABASE mytest;
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
B. Creating a database that specifies the data and transaction log files
The following example creates the database Sales. Because the keyword PRIMARY is not used,
the first file ﴾Sales_dat﴿ becomes the primary file. Because neither MB nor KB is specified in the
SIZE parameter for the Sales_dat file, it uses MB and is allocated in megabytes. The Sales_log
file is allocated in megabytes because the MB suffix is explicitly stated in the SIZE parameter.
USE master;
GO
CREATE DATABASE Sales
ON
( NAME = Sales_dat,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\s
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = Sales_log,
FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\s
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB ) ;
GO
The primary filegroup with the files Spri1_dat and Spri2_dat. The FILEGROWTH
increments for these files are specified as 15%.
This example places the data and log files on different disks to improve performance.
USE master;
GO
CREATE DATABASE Sales
ON PRIMARY
( NAME = SPri1_dat,
FILENAME = 'D:\SalesData\SPri1dat.mdf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 15% ),
( NAME = SPri2_dat,
FILENAME = 'D:\SalesData\SPri2dt.ndf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 15% ),
FILEGROUP SalesGroup1
( NAME = SGrp1Fi1_dat,
FILENAME = 'D:\SalesData\SG1Fi1dt.ndf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 ),
( NAME = SGrp1Fi2_dat,
FILENAME = 'D:\SalesData\SG1Fi2dt.ndf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 ),
FILEGROUP SalesGroup2
( NAME = SGrp2Fi1_dat,
FILENAME = 'D:\SalesData\SG2Fi1dt.ndf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 ),
( NAME = SGrp2Fi2_dat,
FILENAME = 'D:\SalesData\SG2Fi2dt.ndf',
SIZE = 10,
MAXSIZE = 50,
FILEGROWTH = 5 )
LOG ON
( NAME = Sales_log,
FILENAME = 'E:\SalesLog\salelog.ldf',
SIZE = 5MB,
MAXSIZE = 25MB,
FILEGROWTH = 5MB ) ;
GO
E. Attaching a database
The following example detaches the database Archive created in example D, and then attaches
it by using the FOR ATTACH clause. Archive was defined to have multiple data and log files.
However, because the location of the files has not changed since they were created, only the
primary file has to be specified in the FOR ATTACH clause. Beginning with SQL Server 2005, any
full‐text files that are part of the database that is being attached will be attached with the
database.
USE master;
GO
sp_detach_db Archive;
GO
CREATE DATABASE Archive
ON (FILENAME = 'D:\SalesData\archdat1.mdf')
FOR ATTACH ;
GO
The source database for this example is the Sales database created in example D.
USE master;
GO
CREATE DATABASE sales_snapshot0600 ON
( NAME = SPri1_dat, FILENAME = 'D:\SalesData\SPri1dat_0600.ss'),
( NAME = SPri2_dat, FILENAME = 'D:\SalesData\SPri2dt_0600.ss'),
( NAME = SGrp1Fi1_dat, FILENAME = 'D:\SalesData\SG1Fi1dt_0600.ss'),
( NAME = SGrp1Fi2_dat, FILENAME = 'D:\SalesData\SG1Fi2dt_0600.ss'),
( NAME = SGrp2Fi1_dat, FILENAME = 'D:\SalesData\SG2Fi1dt_0600.ss'),
( NAME = SGrp2Fi2_dat, FILENAME = 'D:\SalesData\SG2Fi2dt_0600.ss')
AS SNAPSHOT OF Sales ;
GO
USE master;
GO
IF DB_ID (N'MyOptionsTest') IS NOT NULL
DROP DATABASE MyOptionsTest;
GO
CREATE DATABASE MyOptionsTest
COLLATE French_CI_AI
WITH TRUSTWORTHY ON, DB_CHAINING ON;
GO
‐‐Verifying collation and option settings.
SELECT name, collation_name, is_trustworthy_on, is_db_chaining_on
FROM sys.databases
WHERE name = N'MyOptionsTest';
GO
USE master;
GO
‐‐Detach the AdventureWorks2012 database
sp_detach_db AdventureWorks2012;
GO
‐‐ Physically move the full text catalog to the new location.
‐‐Attach the AdventureWorks2012 database and specify the new location of the full‐text
CREATE DATABASE AdventureWorks2012 ON
(FILENAME = 'c:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Data\
(FILENAME = 'c:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\Data\
(FILENAME = 'c:\myFTCatalogs\AdvWksFtCat')
FOR ATTACH;
GO
USE master;
GO
‐‐ Get the SQL Server data path.
DECLARE @data_path nvarchar(256);
SET @data_path = (SELECT SUBSTRING(physical_name, 1, CHARINDEX(N'master.mdf', LOWER(ph
FROM master.sys.master_files
WHERE database_id = 1 AND file_id = 1);
‐‐ Execute the CREATE DATABASE statement.
EXECUTE ('CREATE DATABASE FileStreamDB
ON PRIMARY
(
NAME = FileStreamDB_data
,FILENAME = ''' + @data_path + 'FileStreamDB_data.mdf''
,SIZE = 10MB
,MAXSIZE = 50MB
,FILEGROWTH = 15%
),
FILEGROUP FileStreamPhotos CONTAINS FILESTREAM DEFAULT
(
NAME = FSPhotos
,FILENAME = ''C:\MyFSfolder\Photos''
‐‐ SIZE and FILEGROWTH should not be specified here.
‐‐ If they are specified an error will be raised.
, MAXSIZE = 5000 MB
),
(
NAME = FSPhotos2
, FILENAME = ''D:\MyFSfolder\Photos''
, MAXSIZE = 10000 MB
),
FILEGROUP FileStreamResumes CONTAINS FILESTREAM
(
NAME = FileStreamResumes
,FILENAME = ''C:\MyFSfolder\Resumes''
)
LOG ON
(
NAME = FileStream_log
,FILENAME = ''' + @data_path + 'FileStreamDB_log.ldf''
,SIZE = 5MB
,MAXSIZE = 25MB
,FILEGROWTH = 5MB
)'
);
GO
Transact‐SQL
USE master;
GO
CREATE DATABASE [BlobStore1]
CONTAINMENT = NONE
ON PRIMARY
(
NAME = N'BlobStore1',
FILENAME = N'C:\BlobStore\BlobStore1.mdf',
SIZE = 100MB,
MAXSIZE = UNLIMITED,
FILEGROWTH = 1MB
),
FILEGROUP [FS] CONTAINS FILESTREAM DEFAULT
(
NAME = N'FS1',
FILENAME = N'C:\BlobStore\FS1',
MAXSIZE = UNLIMITED
),
(
NAME = N'FS2',
FILENAME = N'C:\BlobStore\FS2',
MAXSIZE = 100MB
)
LOG ON
(
NAME = N'BlobStore1_log',
FILENAME = N'C:\BlobStore\BlobStore1_log.ldf',
SIZE = 100MB,
MAXSIZE = 1GB,
FILEGROWTH = 1MB
);
GO
ALTER DATABASE [BlobStore1]
ADD FILE
(
NAME = N'FS3',
FILENAME = N'C:\BlobStore\FS3',
MAXSIZE = 100MB
)
TO FILEGROUP [FS];
GO
See Also
Reference
ALTER DATABASE ﴾Transact‐SQL﴿
DROP DATABASE ﴾Transact‐SQL﴿
EVENTDATA ﴾Transact‐SQL﴿
sp_changedbowner ﴾Transact‐SQL﴿
sp_detach_db ﴾Transact‐SQL﴿
sp_removedbreplication ﴾Transact‐SQL﴿
Concepts
Database Detach and Attach ﴾SQL Server﴿
Database Snapshots ﴾SQL Server﴿
Databases
Binary Large Object ﴾Blob﴿ Data ﴾SQL Server﴿
Other Resources
Move Database Files
© 2016 Microsoft
The SQL Server on‐disk storage format is the same in the 64‐bit and 32‐bit environments.
Therefore, attach works across 32‐bit and 64‐bit environments. A database detached from a server
instance running in one environment can be attached on a server instance that runs in another
environment.
In This Topic:
Security
Detaching a Database
Attaching a Database
Related Tasks
Security
File access permissions are set during a number of database operations, including detaching or
attaching a database.
Security Note
We recommend that you do not attach or restore databases from unknown or untrusted
sources. Such databases could contain malicious code that might execute unintended
Transact‐SQL code or cause errors by modifying the schema or the physical database
structure. Before you use a database from an unknown or untrusted source, run DBCC
CHECKDB on the database on a nonproduction server and also examine the code, such as
stored procedures or other user‐defined code, in the database.
Detaching a Database
Detaching a database removes it from the instance of SQL Server but leaves the database intact
within its data files and transaction log files. These files can then be used to attach the database
to any instance of SQL Server, including the server from which the database was detached.
Note
If you cannot use sp_replicationdboption, you can remove replication by running
sp_removedbreplication.
Before you can detach the database, you must drop all of its snapshots. For more
information, see Drop a Database Snapshot ﴾Transact‐SQL﴿.
Note
The database cannot be detached unless the session is terminated. For more information,
see Removing Database Mirroring ﴾SQL Server﴿.
The database is suspect. A suspect database cannot be detached; before you can detach
it, you must put it into emergency mode. For more information about how to put a
database into emergency mode, see ALTER DATABASE ﴾Transact‐SQL﴿.
1. Reattach all files associated with the database, not just the primary file.
Attaching a Database
You can attach a copied or detached SQL Server database. When you attach a SQL Server 2005
database that contains full‐text catalog files onto a SQL Server 2014 server instance, the catalog
files are attached from their previous location along with the other database files, the same as in
SQL Server 2005. For more information, see Upgrade Full‐Text Search.
When you attach a database, all data files ﴾MDF and NDF files﴿ must be available. If any data file
has a different path from when the database was first created or last attached, you must specify
the current path of the file.
Note
If the primary data file being attached is read‐only, the Database Engine assumes that the
database is read‐only.
When an encrypted database is first attached to an instance of SQL Server, the database owner
must open the master key of the database by executing the following statement: OPEN MASTER
KEY DECRYPTION BY PASSWORD = 'password'. We recommend that you enable automatic
decryption of the master key by executing the following statement: ALTER MASTER KEY ADD
ENCRYPTION BY SERVICE MASTER KEY. For more information, see CREATE MASTER KEY
﴾Transact‐SQL﴿ and ALTER MASTER KEY ﴾Transact‐SQL﴿.
The requirement for attaching log files depends partly on whether the database is read‐write or
read‐only, as follows:
For a read‐write database, you can usually attach a log file in a new location. However, in
some cases, reattaching a database requires its existing log files. Therefore, it is
important to always keep all the detached log files until the database has been
successfully attached without them.
If a read‐write database has a single log file and you do not specify a new location for
the log file, the attach operation looks in the old location for the file. If it is found, the old
log file is used, regardless of whether the database was shut down cleanly. However, if
the old log file is not found and if the database was shut down cleanly and has no active
log chain, the attach operation attempts to build a new log file for the database.
If the primary data file being attached is read‐only, the Database Engine assumes that
the database is read‐only. For a read‐only database, the log file or files must be available
at the location specified in the primary file of the database. A new log file cannot be built
because SQL Server cannot update the log location stored in the primary file.
In This Section:
On attach, database startup occurs. Generally, attaching a database places it in the same state
that it was in when it was detached or copied. However, attach‐and‐detach operations both
disable cross‐database ownership chaining for the database. For information about how to
enable chaining, see cross db ownership chaining Server Configuration Option. Also,
TRUSTWORTHY is set to OFF whenever the database is attached. For information about how
to set TRUSTWORTHY to ON, see ALTER DATABASE ﴾Transact‐SQL﴿.
Important
A database created by a more recent version of SQL Server cannot be attached in earlier
versions.
When you attach a database onto another server instance, to provide a consistent experience
to users and applications, you might have to re‐create some or all of the metadata for the
database, such as logins and jobs, on the other server instance. For more information, see
Manage Metadata When Making a Database Available on Another Server Instance ﴾SQL
Server﴿.
Related Tasks
To detach a database
sp_detach_db ﴾Transact‐SQL﴿
Detach a Database
To attach a database
sp_attach_db ﴾Transact‐SQL﴿
sp_attach_single_file_db ﴾Transact‐SQL﴿
See Also
Database Files and Filegroups
© 2016 Microsoft
Move User
Databases
Move User Databases
SQL Server 2016
In SQL Server, you can move the data, log, and full‐text catalog files of a user database to a new
location by specifying the new file location in the FILENAME clause of the ALTER DATABASE
statement. This method applies to moving database files within the same instance SQL Server. To
move a database to another instance of SQL Server or to another server, use backup and restore or
detach and attach operations.
Considerations
When you move a database onto another server instance, to provide a consistent experience to
users and applications, you might have to re‐create some or all the metadata for the database.
For more information, see Manage Metadata When Making a Database Available on Another
Server Instance ﴾SQL Server﴿.
Some features of the SQL Server Database Engine change the way that the Database Engine
stores information in the database files. These features are restricted to specific editions of SQL
Server. A database that contains these features cannot be moved to an edition of SQL Server
that does not support them. Use the sys.dm_db_persisted_sku_features dynamic management
view to list all edition‐specific features that are enabled in the current database.
The procedures in this topic require the logical name of the database files. To obtain the name,
query the name column in the sys.master_files catalog view.
Starting with SQL Server 2008 R2, full‐text catalogs are integrated into the database rather than
being stored in the file system. The full‐text catalogs now move automatically when you move a
database.
ALTER DATABASE database_name SET OFFLINE;
ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name, FILENAME = 'new_p
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'<database_name>');
ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name , FILENAME = 'new_
2. Stop the instance of SQL Server or shut down the system to perform maintenance. For
more information, see Start, Stop, Pause, Resume, Restart the Database Engine, SQL
Server Agent, or SQL Server Browser Service.
4. Restart the instance of SQL Server or the server. For more information, see Start, Stop,
Pause, Resume, Restart the Database Engine, SQL Server Agent, or SQL Server Browser
Service
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'<database_name>');
Important
If the database cannot be started, that is it is in suspect mode or in an unrecovered state,
only members of the sysadmin fixed role can move the file.
2. Start the instance of SQL Server in master‐only recovery mode by entering one of the
following commands at the command prompt.
NET START MSSQLSERVER /f /T3608
NET START MSSQL$instancename /f /T3608
For more information, see Start, Stop, Pause, Resume, Restart the Database Engine, SQL
Server Agent, or SQL Server Browser Service.
3. For each file to be moved, use sqlcmd commands or SQL Server Management Studio to
run the following statement.
ALTER DATABASE database_name MODIFY FILE( NAME = logical_name , FILENAME = 'new_p
For more information about how to use the sqlcmd utility, see Use the sqlcmd Utility.
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'<database_name>');
Examples
The following example moves the AdventureWorks2012 log file to a new location as part of a
planned relocation.
USE master;
GO
‐‐ Return the logical file name.
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'AdventureWorks2012')
AND type_desc = N'LOG';
GO
ALTER DATABASE AdventureWorks2012 SET OFFLINE;
GO
‐‐ Physically move the file to a new location.
‐‐ In the following statement, modify the path specified in FILENAME to
‐‐ the new location of the file on your server.
ALTER DATABASE AdventureWorks2012
MODIFY FILE ( NAME = AdventureWorks2012_Log,
FILENAME = 'C:\NewLoc\AdventureWorks2012_Log.ldf');
GO
ALTER DATABASE AdventureWorks2012 SET ONLINE;
GO
‐‐Verify the new location.
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'AdventureWorks2012')
AND type_desc = N'LOG';
See Also
ALTER DATABASE ﴾Transact‐SQL﴿
CREATE DATABASE ﴾SQL Server Transact‐SQL﴿
Database Detach and Attach ﴾SQL Server﴿
Move System Databases
Move Database Files
BACKUP ﴾Transact‐SQL﴿
RESTORE ﴾Transact‐SQL﴿
Start, Stop, Pause, Resume, Restart the Database Engine, SQL Server Agent, or SQL Server
Browser Service
© 2016 Microsoft
Move System
Databases
Move System Databases
SQL Server 2016
This topic describes how to move system databases in SQL Server. Moving system databases may
be useful in the following situations:
Failure recovery. For example, the database is in suspect mode or has shut down because of
a hardware failure.
Planned relocation.
The following procedures apply to moving database files within the same instance of SQL Server.
To move a database to another instance of SQL Server or to another server, use the backup and
restore or detach and attach operations.
The procedures in this topic require the logical name of the database files. To obtain the name,
query the name column in the sys.master_files catalog view.
Important
If you move a system database and later rebuild the master database, you must move the
system database again because the rebuild operation installs all system databases to their
default location.
In This Topic
ALTER DATABASE database_name MODIFY FILE ( NAME = logical_name , FILENAME = 'new_
2. Stop the instance of SQL Server or shut down the system to perform maintenance. For
more information, see Start, Stop, Pause, Resume, Restart the Database Engine, SQL
Server Agent, or SQL Server Browser Service.
4. Restart the instance of SQL Server or the server. For more information, see Start, Stop,
Pause, Resume, Restart the Database Engine, SQL Server Agent, or SQL Server Browser
Service.
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'<database_name>');
If the msdb database is moved and the instance of SQL Server is configured for Database Mail,
complete these additional steps.
1. Verify that Service Broker is enabled for the msdb database by running the following
query.
SELECT is_broker_enabled
FROM sys.databases
WHERE name = N'msdb';
For more information about enabling Service Broker, see ALTER DATABASE ﴾Transact‐
SQL﴿.
2. Verify that Database Mail is working by sending a test mail.
Important
2. Start the instance of SQL Server in master‐only recovery mode by entering one of the
following commands at the command prompt. The parameters specified in these
commands are case sensitive. The commands fail when the parameters are not specified
as shown.
NET START MSSQLSERVER /f /T3608
NET START MSSQL$instancename /f /T3608
For more information, see Start, Stop, Pause, Resume, Restart the Database Engine, SQL
Server Agent, or SQL Server Browser Service.
3. For each file to be moved, use sqlcmd commands or SQL Server Management Studio to
run the following statement.
ALTER DATABASE database_name MODIFY FILE( NAME = logical_name , FILENAME = 'new_p
For more information about using the sqlcmd utility, see Use the sqlcmd Utility.
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'<database_name>');
1. From the Start menu, point to All Programs, point to Microsoft SQL Server, point to
Configuration Tools, and then click SQL Server Configuration Manager.
2. In the SQL Server Services node, right‐click the instance of SQL Server ﴾for example, SQL
Server ﴾MSSQLSERVER﴿﴿ and choose Properties.
3. In the SQL Server ﴾instance_name﴿ Properties dialog box, click the Startup Parameters
tab.
4. In the Existing parameters box, select the –d parameter to move the master data file.
Click Update to save the change.
In the Specify a startup parameter box, change the parameter to the new path of the
master database.
5. In the Existing parameters box, select the –l parameter to move the master log file. Click
Update to save the change.
In the Specify a startup parameter box, change the parameter to the new path of the
master database.
The parameter value for the data file must follow the ‐d parameter and the value for the
log file must follow the ‐l parameter. The following example shows the parameter values
for the default location of the master data file.
‐dC:\Program Files\Microsoft SQL
Server\MSSQL<version>.MSSQLSERVER\MSSQL\DATA\master.mdf
‐lC:\Program Files\Microsoft SQL
Server\MSSQL<version>.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
If the planned relocation for the master data file is E:\SQLData, the parameter values
would be changed as follows:
‐dE:\SQLData\master.mdf
‐lE:\SQLData\mastlog.ldf
6. Stop the instance of SQL Server by right‐clicking the instance name and choosing Stop.
9. Verify the file change for the master database by running the following query.
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID('master');
GO
Change the SQL Server Agent log path. If you do not update this path, SQL Server Agent
will fail to start.
Change the database default location. Creating a new database may fail if the drive letter
and path specified as the default location do not exist.
1. From SQL Server Management Studio, in Object Explorer, expand SQL Server Agent.
3. In the Configure SQL Server Agent Error Logs dialog box, specify the new location of
the SQLAGENT.OUT file. The default location is C:\Program Files\Microsoft SQL
Server\MSSQL<version>.<instance_name>\MSSQL\Log\.
Change the database default location
1. From SQL Server Management Studio, in Object Explorer, right‐click the SQL Server
server and click Properties.
3. Under Database Default Locations, browse to the new location for both the data and
log files.
4. Stop and start the SQL Server service to complete the change.
Examples
Note
Because tempdb is re‐created each time the instance of SQL Server is started, you do not
have to physically move the data and log files. The files are created in the new location
when the service is restarted in step 3. Until the service is restarted, tempdb continues to
use the data and log files in existing location.
1. Determine the logical file names of the tempdb database and their current location on
the disk.
SELECT name, physical_name AS CurrentLocation
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');
GO
USE master;
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = tempdev, FILENAME = 'E:\SQLData\tempdb.mdf');
GO
ALTER DATABASE tempdb
MODIFY FILE (NAME = templog, FILENAME = 'F:\SQLLog\templog.ldf');
GO
SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'tempdb');
5. Delete the tempdb.mdf and templog.ldf files from the original location.
See Also
Resource Database
tempdb Database
master Database
msdb Database
model Database
Move User Databases
Move Database Files
Start, Stop, Pause, Resume, Restart the Database Engine, SQL Server Agent, or SQL Server
Browser Service
ALTER DATABASE ﴾Transact‐SQL﴿
Rebuild System Databases
© 2016 Microsoft