An example use case for the process below could be you need to move database files to a new drive. Another example might be your organisation intends to run a legacy database along side a new updated database with both sharing the same database name in the same instance with the files located in the same directory with the same names. Obviously this cannot be done and requires the database names to differ and the files to be renamed or not exist in the same directory.
For example AdventureWorks might become AdventureWorks_Legacy while a new and improved AdventureWorks database retains the original database name. The associated database file names would also need to be changed/moved to reflect this.
Someone might also want to do something like this for test purposes but obviously having test resources in a live environment would not be recommended if avoidable.
The first step to moving and renaming the files is to copy and modify the script below. Note the script below assumes you want to move and change the names of the files. To avoid any database conflicts you only need to do one or the other.
/* Find & Replace DbName with the name of the Database you are working with */ USE [DbName]; /* Changing Physical names and paths Replace 'C:\...\NewDbName.mdf' with full path of new Db file to be used */ ALTER DATABASE DbName MODIFY FILE ( NAME = ' DbName ' ,FILENAME = 'C:\...\NewDbName.mdf' ); /* Replace 'C:\...\NewDbName_log.ldf' with full path of new Db log file to be used */ ALTER DATABASE DbName MODIFY FILE ( NAME = ' DbName _log' ,FILENAME = 'C:\...\NewDbName_log.ldf' ); /* Changing logical names */ ALTER DATABASE DbName MODIFY FILE ( NAME = DbName ,NEWNAME = NewDbName ); ALTER DATABASE DbName MODIFY FILE ( NAME = DbName_log ,NEWNAME = NewDbName_log );
- Open Microsoft SQL Server Management Studio (SSMS).
- Connect to the server that houses the Db you are working with.
- Run the modified script
- Right click on the Db in SSMS and select Tasks > Take Offline
- If you are moving the database files log into the server that houses the database files and copy and move the MDF and LDF files to the location you specified in first two alter commands. If the script specifies new names rename the copied files to match the names given in the script exactly.
- Go back to SSMS and right click on the Db and select Tasks > Bring Online.
- If you have moved the files once the database is back online and confirmed working as expected the unused original files can be deleted.
- Now you can rename the Db to the new name if you wish using SSMS.