Attach and Detach
Attach and Detach
By Alexander Chigrik
Introduction
If you need to move a database, or database file to another server or disk, and you
do not want to backup the database, copy the backup on another server, and then re-
create the database from the backup, you can use the sp_detach_db and sp_attach_db
system stored procedures to detach the database and then attach it again. Detaching
and attaching databases can be used when you want to move the database files to a
different physical disk from the disk that has run out of disk space and you want
to expand the existing file rather than add a new file to the database on another
disk.
To move a database using detach and attach, you should make the following steps:
Detaching a Database
To detach an SQL Server 2000 database, you can use the sp_detach_db system stored
procedure. This stored procedure can also run UPDATE STATISTICS on all tables
before detaching. The syntax for sp_detach_db system stored procedure is as
follows:
When you attach a database, you must specify at least the name and physical
location of the primary data file. If one or more of the database files have
changed location since the database was detached, you must specify the name and
physical location of these files in addition to the primary file.
To attach SQL Server 2000 database, you can use the sp_attach_db system stored
procedure. The syntax for sp_attach_db system stored procedure is as follows:
A single-file database is a database that has only one data file. When a database
comprises only one data file , the database can be attached to an instance of SQL
Server 2000 without using the transaction log file. When the data file will be
attached, SQL Server will create a new transaction log file automatically.
When you move a database to another server and there are existing users in the
detached database, you can lose users after attaching the database on the new
server. For example, if you move the Sales database from the Product server to the
Test server (for the test purposes) and the user Alex exists in the Sales database,
you should manually link the relationship between the Alex user and the appropriate
login on the Test server.
You can use the sp_change_users_login system stored procedure to link the specified
user in the current database to the appropriate login. The following example links
the user Alex in the current database to the Alex login: