Database/MS-SQL

[스크랩] Create database for attach

99iberty 2015. 7. 30. 18:50

https://msdn.microsoft.com/en-us/library/ms176061.aspx


Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
Expand Minimize

CREATE DATABASE (SQL Server Transact-SQL)

 

Applies To: SQL Server 2014, SQL Server 2016 Preview

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).

Topic link icon Transact-SQL Syntax Conventions

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_OPTIMIZED_DATA ]
    <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
[;]

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.

database_name can be a maximum of 128 characters, unless a logical name is not specified for the log file. If a logical log file name is not specified, SQL Server generates the logical_file_name and the os_file_name for the log by appending a suffix to database_name. This limits database_name to 123 characters so that the generated logical file name is no more than 128 characters.

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.

CONTAINMENT = { NONE | PARTIAL }

Applies to: SQL Server 2012 through SQL Server 2016.

Specifies the containment status of the database. NONE = non-contained database. PARTIAL = partially contained database.

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).

LOG on cannot be specified on a database snapshot.

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.

A collation name cannot be specified with the FOR ATTACH or FOR ATTACH_REBUILD_LOG clauses. For information about how to change the collation of an attached database, visit this Microsoft Web site.

For more information about the Windows and SQL collation names, see COLLATE (Transact-SQL).

System_CAPS_noteNote

Contained databases are collated differently than non-contained databases. Please see Contained Database Collations for more information.

WITH <option>
  • <filestream_options>

    NON_TRANSACTED_ACCESS = { OFF | READ_ONLY | FULL }

    Applies to: SQL Server 2012 through SQL Server 2016.

    Specifies the level of non-transactional FILESTREAM access to the database.

    Value

    Description

    OFF

    Non-transactional access is disabled.

    READONLY

    FILESTREAM data in this database can be read by non-transactional processes.

    FULL

    Full non-transactional access to FILESTREAM FileTables is enabled.

    DIRECTORY_NAME = <directory_name>

    Applies to: SQL Server 2012 through SQL Server 2016.

    A windows-compatible directory name. This name should be unique among all the Database_Directory names in the SQL Server instance. Uniqueness comparison is case-insensitive, regardless of SQL Server collation settings. This option should be set before creating a FileTable in this database.

The following options are allowable only when CONTAINMENT has been set to PARTIAL. If CONTAINMENT is set to NONE, errors will occur.

  • DEFAULT_FULLTEXT_LANGUAGE = <lcid> | <language name> | <language alias>

    Applies to: SQL Server 2012 through SQL Server 2016.

    See Configure the default full-text language Server Configuration Option for a full description of this option.

  • DEFAULT_LANGUAGE = <lcid> | <language name> | <language alias>

    Applies to: SQL Server 2012 through SQL Server 2016.

    See Configure the default language Server Configuration Option for a full description of this option.

  • NESTED_TRIGGERS = { OFF | on}

    Applies to: SQL Server 2012 through SQL Server 2016.

    See Configure the nested triggers Server Configuration Option for a full description of this option.

  • TRANSFORM_NOISE_WORDS = { OFF | on}

    Applies to: SQL Server 2012 through SQL Server 2016.

    See transform noise words Server Configuration Optionfor a full description of this option.

  • TWO_DIGIT_YEAR_CUTOFF = { 2049 | <any year between 1753 and 9999> }

    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 }

    When on is specified, the database can be the source or target of a cross-database ownership chain.

    When OFF, the database cannot participate in cross-database ownership chaining. The default is OFF.

    System_CAPS_importantImportant

    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 }

    When on is specified, database modules (for example, views, user-defined functions, or stored procedures) that use an impersonation context can access resources outside the database.

    When OFF, database modules in an impersonation context cannot access resources outside the database. The default is OFF.

    TRUSTWORTHY is set to OFF whenever the database is attached.

    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.

FOR ATTACH [ WITH < attach_database_option > ]

Specifies that the database is created by attaching an existing set of operating system files. There must be a <filespec> entry that specifies the primary file. The only other <filespec> entries required are those for any files that have a different path from when the database was first created or last attached. A <filespec> entry must be specified for these files.

FOR ATTACH requires the following:

  • All data files (MDF and NDF) must be available.

  • If multiple log files exist, they must all be available.

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.

System_CAPS_noteNote

A database created by a more recent version of SQL Server cannot be attached in earlier versions.

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 cannot be specified on a database snapshot.

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.

System_CAPS_noteNote

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. 

System_CAPS_noteNote

The TRUSTWORTHY and DB_CHAINING options have no affect when attaching a database.

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).

System_CAPS_noteNote

If the log files are available, the Database Engine uses those files instead of rebuilding the log files.

FOR ATTACH_REBUILD_LOG requires the following:

  • A clean shutdown of the database.

  • All data files (MDF and NDF) must be available.

System_CAPS_importantImportant

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 ATTACH_REBUILD_LOG cannot be specified on a database snapshot.

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.

FILENAME { 'os_file_name' | 'filestream_path' }

Specifies the operating system (physical) file name.

'os_file_name' 

Is the path and file name used by the operating system when you create the file. The file must reside on one of the following devices: the local server on which SQL Server is installed, a Storage Area Network [SAN], or an iSCSI-based network. The specified path must exist before executing the CREATE DATABASE statement. For more information, see "Database Files and Filegroups" in the Remarks section.

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.

'filestream_path'

For a FILESTREAM filegroup, FILENAME refers to a path where FILESTREAM data will be stored. The path up to the last folder must exist, and the last folder must not exist. For example, if you specify the path C:\MyFiles\MyFilestreamData, C:\MyFiles must exist before you run ALTER DATABASE, but the MyFilestreamData folder must not exist.

The filegroup and file (<filespec>) must be created in the same statement.

The SIZE and FILEGROWTH properties do not apply to a FILESTREAM filegroup.

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. 

System_CAPS_noteNote

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.

A value of 0 indicates that automatic growth is off and no additional space is allowed.

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.

System_CAPS_noteNote

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

Applies to: SQL Server 2014 through SQL Server 2016.

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.

ON ( NAME = logical_file_name, FILENAME = 'os_file_name' ) [ ,... n ]

For creating a database snapshot, specifies a list of files in the source database. For the snapshot to work, all the data files must be specified individually. However, log files are not allowed for database snapshots. FILESTREAM filegroups are not supported by database snapshots. If a FILESTREAM data file is included in a CREATE DATABASE on clause, the statement will fail and an error will be raised.

For descriptions of NAME and FILENAME and their values see the descriptions of the equivalent <filespec> values.

System_CAPS_noteNote

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.

For more information, see "Database Snapshots" in the Remarks section.

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.

  2. A service broker GUID is assigned to the database.

  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.

Every database has at least two files, a primary file and a transaction log file, and at least one filegroup. A maximum of 32,767 files and 32,767 filegroups can be specified for each database.

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.



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.

System_CAPS_noteNote

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).

Each snapshot persists until it is deleted by using DROP DATABASE.

For more information, see Database Snapshots (SQL Server).

Several database options are automatically set whenever you create a database. For a list of these options, see ALTER DATABASE SET Options (Transact-SQL).

All user-defined objects in the model database are copied to all newly created databases. You can add any objects, such as tables, views, stored procedures, data types, and so on, to the model database to be included in all newly created databases.

When a CREATE DATABASE database_name statement is specified without additional size parameters, the primary data file is made the same size as the primary file in the model database.

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.

You can use catalog views, system functions, and system stored procedures to return information about databases, files, and filegroups. For more information, see System Views (Transact-SQL).

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

In SQL Server, certain permissions are set on the data and log files of each database. The following permissions are set whenever the following operations are applied to a database:

Created

Modified to add a new file

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.

System_CAPS_noteNote

Microsoft SQL Server 2005 Express Edition does not set data and log file permissions.

The following example creates the database mytest and creates a corresponding primary and transaction log file. Because the statement has no <filespec> items, the primary database file is the size of the model database primary file. The transaction log is set to the larger of these values: 512KB or 25% the size of the primary data file. Because MAXSIZE is not specified, the files can grow to fill all available disk space. This example also demonstrates how to drop the database named mytest if it exists, before creating the mytest database.

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

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\MSSQL13.MSSQLSERVER\MSSQL\DATA\saledat.mdf',
    SIZE = 10,
    MAXSIZE = 50,
    FILEGROWTH = 5 )
LOG on
( NAME = Sales_log,
    FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\DATA\salelog.ldf',
    SIZE = 5MB,
    MAXSIZE = 25MB,
    FILEGROWTH = 5MB ) ;
GO

The following example creates the database Archive that has three 100-MB data files and two 100-MB transaction log files. The primary file is the first file in the list and is explicitly specified with the PRIMARY keyword. The transaction log files are specified following the LOG on keywords. Note the extensions used for the files in the FILENAME option: .mdf is used for primary data files, .ndf is used for the secondary data files, and .ldf is used for transaction log files. This example places the database on the D: drive instead of with the master database.

USE master;
GO
CREATE DATABASE Archive 
on
PRIMARY  
    (NAME = Arch1,
    FILENAME = 'D:\SalesData\archdat1.mdf',
    SIZE = 100MB,
    MAXSIZE = 200,
    FILEGROWTH = 20),
    ( NAME = Arch2,
    FILENAME = 'D:\SalesData\archdat2.ndf',
    SIZE = 100MB,
    MAXSIZE = 200,
    FILEGROWTH = 20),
    ( NAME = Arch3,
    FILENAME = 'D:\SalesData\archdat3.ndf',
    SIZE = 100MB,
    MAXSIZE = 200,
    FILEGROWTH = 20)
LOG on 
   (NAME = Archlog1,
    FILENAME = 'D:\SalesData\archlog1.ldf',
    SIZE = 100MB,
    MAXSIZE = 200,
    FILEGROWTH = 20),
   (NAME = Archlog2,
    FILENAME = 'D:\SalesData\archlog2.ldf',
    SIZE = 100MB,
    MAXSIZE = 200,
    FILEGROWTH = 20) ;
GO

The following example creates the database Sales that has the following filegroups:

  • The primary filegroup with the files Spri1_dat and Spri2_dat. The FILEGROWTH increments for these files are specified as 15%.

  • A filegroup named SalesGroup1 with the files SGrp1Fi1 and SGrp1Fi2.

  • A filegroup named SalesGroup2 with the files SGrp2Fi1 and SGrp2Fi2.

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

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 following example creates the database snapshot sales_snapshot0600. Because a database snapshot is read-only, a log file cannot be specified. In conformance with the syntax, every file in the source database is specified, and filegroups are not specified.

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

The following example creates the database MyOptionsTest. A collation name is specified and the TRUSTYWORTHY and DB_CHAINING options are set to ON.

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

The following example attaches the full-text catalog AdvWksFtCat along with the AdventureWorks2012 data and log files. In this example, the full-text catalog is moved from its default location to a new location c:\myFTCatalogs. The data and log files remain in their default locations.

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 catalog.
CREATE DATABASE AdventureWorks2012 on 
    (FILENAME = 'c:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\AdventureWorks2012_data.mdf'), 
    (FILENAME = 'c:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Data\AdventureWorks2012_log.ldf'),
    (FILENAME = 'c:\myFTCatalogs\AdvWksFtCat')
FOR ATTACH;
GO

The following example creates the FileStreamDB database. The database is created with one row filegroup and two FILESTREAM filegroups. Each filegroup contains one file:

  • FileStreamDB_data contains row data. It contains one file, FileStreamDB_data.mdf with the default path.

  • FileStreamPhotos contains FILESTREAM data. It contains two FILESTREAM data containers, FSPhotos, located at C:\MyFSfolder\Photos and FSPhotos2, located at D:\MyFSfolder\Photos. It is marked as the default FILESTREAM filegroup.

  • FileStreamResumes contains FILESTREAM data. It contains one FILESTREAM data container, FSResumes, located at C:\MyFSfolder\Resumes.

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(physical_name)) - 1)
                  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

The following example creates the BlobStore1 database. The database is created with one row filegroup and one FILESTREAM filegroup, FS. The FILESTREAM filegroup contains two files, FS1 and FS2. Then the database is altered by adding a third file, FS3, to the FILESTREAM filegroup.

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

Community Additions

ADD
Show:
© 2015 Microsoft



---------


https://msdn.microsoft.com/ko-kr/library/ms190209(v=SQL.120).aspx



이 페이지가 유용했습니까?
이 콘텐츠에 대한 여러분의 의견은 중요합니다. 의견을 알려주십시오.
추가 의견
1500자 남음
이 문서는 수동으로 번역한 것입니다. 원본 텍스트를 보려면 포인터를 문서의 문장 위로 올리십시오. 추가 정보
번역
원본
정보
요청한 주제가 아래에 표시됩니다. 그러나 이 주제는 이 라이브러리에 포함되지 않습니다.

데이터베이스 연결

이 항목에서는 SQL Server Management Studio 또는 Transact-SQL을 사용하여 SQL Server 2014의 데이터베이스를 연결하는 방법에 대해 설명합니다. 이 기능을 사용하여 SQL Server 데이터베이스를 복사, 이동 또는 업그레이드할 수 있습니다.

항목 내용


사전 요구 사항

  • 먼저 데이터베이스를 분리해야 합니다. 분리되지 않은 데이터베이스를 연결하려고 하면 오류가 반환됩니다. 자세한 내용은 데이터베이스 분리를 참조하십시오.

  • 데이터베이스를 연결할 경우 모든 데이터 파일(MDF 및 LDF 파일)이 사용 가능해야 합니다. 데이터베이스가 처음 생성되었을 때 또는 마지막으로 연결되었을 때와 경로가 다른 데이터 파일이 있으면 해당 파일의 현재 경로를 지정해야 합니다.

  • 데이터베이스를 분리하는 경우 MDF 및 LDF 파일이 서로 다른 디렉터리에 있고 경로 중 하나에 \\? \GlobalRoot가 포함되어 있으면 작업이 실패합니다.

권장 사항

데이터베이스를 이동할 때는 분리 및 연결 작업 사용 대신 계획된 ALTER DATABASE 재배치 프로시저를 사용하는 것이 좋습니다. 자세한 내용은 사용자 데이터베이스 이동을 참조하십시오.

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘 [맨 위로 이동]

보안

파일 액세스 권한은 데이터베이스 분리, 연결 등의 여러 데이터베이스 작업 중에 설정됩니다. 데이터베이스를 분리 및 연결할 때마다 설정되는 파일 사용 권한에 대한 자세한 내용은 SQL Server 2008 R2 온라인 설명서에서 데이터 및 로그 파일 보안을 참조하십시오.

알 수 없거나 신뢰할 수 없는 출처의 데이터베이스는 연결하거나 복원하지 않는 것이 좋습니다. 이러한 데이터베이스에 포함된 악성 코드가 의도하지 않은 Transact-SQL 코드를 실행하거나 스키마 또는 물리적 데이터베이스 구조를 수정하여 오류가 발생할 수 있습니다. 알 수 없거나 신뢰할 수 없는 소스의 데이터베이스를 사용하기 전에 비프로덕션 서버의 데이터베이스에서 DBCC CHECKDB를 실행하여 데이터베이스에서 코드(예: 저장 프로시저 또는 다른 사용자 정의 코드)를 시험해 보십시오. 데이터베이스 연결에 대한 자세한 내용 및 데이터베이스를 연결할 때 메타데이터에 대해 이루어지는 변경에 대한 자세한 내용은 데이터베이스 분리 및 연결(SQL Server)을 참조하십시오.

사용 권한

CREATE DATABASE, CREATE ANY DATABASE 또는 ALTER ANY DATABASE 권한이 필요합니다.

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘 [맨 위로 이동]

데이터베이스를 연결하려면

  1. SQL Server Management Studio 개체 탐색기에서 SQL Server 데이터베이스 엔진의 인스턴스에 연결한 다음 해당 인스턴스를 확장합니다.

  2. 마우스 오른쪽 단추로 데이터베이스를 클릭하고 연결을 클릭합니다.

  3. 데이터베이스 연결 대화 상자에서 연결할 데이터베이스를 지정하려면 추가를 클릭하고 데이터베이스 파일 찾기 대화 상자에서 데이터베이스가 있는 디스크 드라이브를 선택한 다음 디렉터리 트리를 확장하여 데이터베이스의 .mdf 파일을 선택합니다. 파일의 경로를 예로 들면 다음과 같습니다.

    C:\Program Files\Microsoft SQL Server\MSSQL12.MSSQLSERVER\MSSQL\DATA\AdventureWorks2012_Data.mdf

    중요 정보 중요

    이미 연결된 데이터베이스를 선택하려고 하면 오류가 발생합니다.

    연결할 데이터베이스

    선택한 데이터베이스에 대한 정보를 표시합니다.

    <no column header>

    연결 작업의 상태를 나타내는 아이콘을 표시합니다. 가능한 아이콘은 아래의 상태에 대한 설명에 설명되어 있습니다.

    MDF 파일 위치

    선택한 MDF 파일의 경로와 파일 이름을 표시합니다.

    데이터베이스 이름

    데이터베이스 이름을 표시합니다.

    다른 이름으로 연결

    필요에 따라 연결할 데이터베이스의 이름을 다른 이름으로 지정합니다.

    소유자

    필요에 따라 다른 소유자를 선택할 수 있도록 가능한 데이터베이스 소유자의 드롭다운 목록을 제공합니다.

    상태

    다음 표에 설명된 내용과 같이 데이터베이스의 상태를 표시합니다.

    아이콘

    상태 텍스트

    설명

    (아이콘 없음)

    (텍스트 없음)

    연결 작업이 시작되지 않았거나 이 개체에 대해 보류 중입니다. 대화 상자가 열려 있는 경우에 표시되는 기본 설정입니다.

    녹색, 오른쪽 방향 삼각형

    진행 중

    연결 작업이 시작되었지만 아직 완료되지 않았습니다.

    녹색 확인 표시

    성공

    개체가 성공적으로 연결되었습니다.

    흰색 십자 표시가 있는 빨강 원

    오류

    연결 작업을 수행하는 동안 오류가 발생하여 완료하지 못했습니다.

    오른쪽과 왼쪽에 두 개의 검정 사분면이 있고 위쪽과 아래쪽에 두 개의 흰색 사분면이 있는 원

    중지됨

    사용자가 작업을 중지하여 연결 작업이 완료되지 않았습니다.

    시계 반대 방향을 가리키는 곡선 모양의 화살표가 있는 원

    롤백됨

    연결 작업이 성공적으로 완료되었지만 다른 개체를 연결하는 동안 발생한 오류로 인해 롤백되었습니다.

    메시지

    빈 메시지 또는 "파일을 찾을 수 없습니다"라는 하이퍼링크를 표시합니다.

    추가

    필요한 기본 데이터베이스 파일을 찾습니다. 사용자가 .mdf 파일을 선택하면 연결할 데이터베이스 표의 각 필드에 적절한 정보가 자동으로 입력됩니다.

    제거

    선택한 파일을 연결할 데이터베이스 표에서 제거합니다.

    " <database_name> " 데이터베이스 정보

    연결할 파일의 이름을 표시합니다. 파일의 경로 이름을 확인하거나 변경하려면 찾아보기 단추()를 클릭합니다.

    참고 참고

    파일이 없으면 메시지 열에 "찾을 수 없음"이 표시됩니다. 로그 파일을 찾을 수 없는 경우 다른 디렉터리에 있거나 삭제된 것입니다. 올바른 위치를 가리키도록 데이터베이스 정보 표의 파일 경로를 업데이트하거나 표에서 로그 파일을 제거해야 합니다. .ndf 데이터 파일을 찾을 수 없는 경우 올바른 위치를 가리키도록 표에서 해당 파일의 경로를 업데이트해야 합니다.

    원래 파일 이름

    데이터베이스에 속한 연결된 파일의 이름을 표시합니다.

    파일 유형

    파일의 형식(데이터 또는 로그)을 나타냅니다.

    현재 파일 경로

    선택한 데이터베이스 파일의 경로를 표시합니다. 이 경로는 직접 편집할 수 있습니다.

    메시지

    빈 메시지 또는 "파일을 찾을 수 없습니다"라는 하이퍼링크를 표시합니다.

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘 [맨 위로 이동]

데이터베이스를 연결하려면

  1. 데이터베이스 엔진에 연결합니다.

  2. 표준 도구 모음에서 새 쿼리를 클릭합니다.

  3. FOR ATTACH 절과 함께 CREATE DATABASE 문을 사용합니다.

    다음 예를 복사하여 쿼리 창에 붙여 넣고 실행을 클릭합니다. 이 예에서는 AdventureWorks2012 데이터베이스의 파일을 연결하고 데이터베이스 이름을 MyAdventureWorks로 바꿉니다.

    CREATE DATABASE MyAdventureWorks 
        ON (FILENAME = 'C:\MySQLServer\AdventureWorks_Data.mdf'), 
        (FILENAME = 'C:\MySQLServer\AdventureWorks_Log.ldf') 
        FOR ATTACH; 
    
    참고참고

    또는 sp_attach_db 또는 sp_attach_single_file_db 저장 프로시저를 사용할 수 있습니다. 그러나 이 프로시저는 이후 버전의 Microsoft SQL Server에서 제거될 예정입니다. 새 개발 작업에서는 이 기능을 사용하지 않도록 하고, 현재 이 기능을 사용하는 응용 프로그램은 수정하십시오. 대신 CREATE DATABASE … FOR ATTACH를 사용하는 것이 좋습니다.

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘 [맨 위로 이동]

연결 방법을 사용하여 데이터베이스를 업그레이드하면 데이터베이스를 바로 사용할 수 있으며 자동으로 업그레이드됩니다. 데이터베이스에 전체 텍스트 인덱스가 있는 경우 업그레이드 프로세스는 전체 텍스트 업그레이드 옵션 서버 속성의 설정에 따라 인덱스를 가져오거나, 다시 설정하거나, 다시 작성합니다. 업그레이드 옵션이 가져오기 또는 다시 작성으로 설정되어 있는 경우 업그레이드하는 동안 전체 텍스트 인덱스를 사용할 수 없습니다. 인덱싱되는 데이터 양에 따라 가져오기 작업은 몇 시간씩 걸릴 수 있으며 다시 작성 작업은 10배 정도 더 걸릴 수 있습니다. 업그레이드 옵션이 가져오기로 설정되어 있으면 전체 텍스트 카탈로그를 사용할 수 없는 경우 관련된 전체 텍스트 인덱스가 다시 작성됩니다.

사용자 데이터베이스의 호환성 수준이 업그레이드 이전에 100 이상이면 업그레이드 후에도 동일하게 유지됩니다. 업그레이드 이전에 호환성 수준이 90이면 업그레이드된 데이터베이스에서는 호환성 수준이 SQL Server 2014에서 지원되는 가장 낮은 호환성 수준인 100으로 설정됩니다. 자세한 내용은 ALTER DATABASE 호환성 수준(Transact-SQL)을 참조하십시오.

맨 위로 이동 링크와 함께 사용되는 화살표 아이콘 [맨 위로 이동]

커뮤니티 추가 항목

표시:
© 2015 Microsoft