It happens sometimes that we need to rename a database. It is good to know that what happens behind the scenes is different from what you may be expecting.
SQL Server renames the presenting name of the DB only. The problem happens when you want to create a DB with the old name. For instance, imagine you have a DB called
MyDB. You rename it to MyDB_OLD. Now you try to create a new DB called MyDB. This operation fails because the underlying
files of the MyDB_OLD are yet MyDB.mdf and MyDB_log.ldf. If you take the DB offline and physically rename the files, when you try to bring it back online,
it fails because the new file name does not match the one saved inside the file!
And here is the question again: how can we rename a DB and all its physical files?
In order to do that, you need to follow these steps:
- Open Microsoft SQL Server Management Studio.
- Connect to the server wherein the DB you want to rename is located.
- Modify the following script and run it –
ALTER DATABASE MyDB MODIFY FILE (NAME = ' MyDB ', FILENAME = 'C:\...\NewMyDB.mdf');
ALTER DATABASE MyDB MODIFY FILE (NAME = ' MyDB _log', FILENAME = 'C:\...\NewMyDB_log.ldf');
ALTER DATABASE MyDB MODIFY FILE (NAME = MyDB, NEWNAME = NewMyDB);
ALTER DATABASE MyDB MODIFY FILE (NAME = MyDB _log, NEWNAME = NewMyDB_log);
- Right click on the DB and select Tasks>Take Offline
- Go to the location that MDF and LDF files are located and rename them exactly as you specified in first two alter commands. If you changed the folder path,
then you need to move them there.
- Go back to Microsoft SQL Server Management Studio and right click on the DB and select Tasks>Bring Online.
- Now is the time to rename you DB to the new name.