Attaches a database to a server.
This feature will be removed in a future version of Microsoft SQL Server. Avoid using this feature in new development work, and plan to modify applications that currently use this feature. We recommend that you use CREATE DATABASE database_name FOR ATTACH instead. For more information, see CREATE DATABASE (Transact-SQL).
To rebuild multiple log files when one or more have a new location, use CREATE DATABASE database_name FOR ATTACH_REBUILD_LOG.
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.
The sp_attach_db stored procedure should only be executed on databases that were previously detached from the database server by using an explicit sp_detach_db operation or on copied databases. If you have to specify more than 16 files, use CREATE DATABASE database_name FOR ATTACH or CREATE DATABASE database_name FOR_ATTACH_REBUILD_LOG. For more information, see CREATE DATABASE (Transact-SQL).
Any unspecified file is assumed to be in its last known location. To use a file in a different location, you must specify the new location.
A database created by a more recent version of SQL Server cannot be attached in earlier versions.
A database snapshot cannot be detached or attached.
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.
The source database must be at least version 80 (SQL Server 2000) to attach to SQL Server 2008 R2, SQL Server 2008. SQL Server 2000 or SQL Server 2005 databases that have a compatibility level less than 80 will be set to compatibility 80 when attached.
For information about how permissions are handled when a database is attached, see CREATE DATABASE (Transact-SQL).
The following example attaches files from AdventureWorks2008R2 to the current server.
EXEC sp_attach_db @dbname = N'AdventureWorks2008R2', @filename1 = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\AdventureWorks2008R2_Data.mdf', @filename2 = N'C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Data\AdventureWorks2008R2_log.ldf';