Move a database file


* Important *

Before attempting to move a database file please ensure that you have a good backup to go back to should things go wrong.


The procedure for moving a database file varies depending on whether you want to:


Move a database file

This procedure can be used for any database except 'tempdb' or 'master':

To move one or more database files for a given database:

  1. Consider backing up the database before you start, in case anything goes wrong.
  2. Get a list of all the filenames for files currently used in the database. Do this using:

Use MyDatabase

Go

Exec sp_helpfile

This step is essential - you can only successfully reattach the database by specifying each and every file.

  1. Detach the database. This prevents others from using it while the files are being moved. Do this using:

Exec sp_detach_db 'MyDatabase'

You will not be able to detach a database whilst it is in use.

  1. Move the database files to their new location, or rename them, as  appropriate to your needs.
  2. Reattach the database, explicitly specifying the full pathname of every file that constitutes the database. This includes any files that were not moved or renamed. For example:

Exec sp_attach_db 'MyDatabase',

    'E:\MsSql7\NewHome\MyDatabase_Data.mdf',

    'E:\MsSql7\NewHome\MyDatabase_Log.ldf'

Notes:


Move master database files

Procedure to move the master database:

  1. Take a full backup that you are confident you can recover from, incase anything goes wrong.
  2. Stop MS Sql Server.
  3. Move the files that constitute the master database to their new location and/or rename them, as appropriate.
  4. Change the start-up parameters for SQL Server to reflect the change.
  5. The easiest way to do this is to edit the parameters in the registry, under:

HKEY_LOCAL_MACHINE

    \SOFTWARE

        \Microsoft

            \MSSQLServer

                \MSSQLServer

                    \Parameters

Typical parameters are:

SQLArg0 -dc:\MSSQL7\data\master.mdf

SQLArg1 -ec:\MSSQL7\log\ERRORLOG

SQLArg2 -lc:\MSSQL7\data\masterlog.ldf

  1. Restart MS Sql Server.
  2. Whilst it should be unnecessary, for confidence you may wish to check the database:

dbcc checkdb (master) with no_infomsgs


Move temporary database files

To move a file that constitutes part of the temporary database use:

Alter database tempdb modify file

(name=<logical-name>, filename='<full-pathname>')

For example:

Alter database tempdb modify file

(name=templog, filename='e:\mssql\data\templog.ldf')

This change will take affect when the MS SQL Server is next restarted.


These notes have been tested against SQL Server 7.