SQL: How to rename a database, including file names

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. The SQL Server renames the presenting name of the DB only, but not the file names.

To rename the files, you need to use the following script to rename the files of OldDB to NewDB.

USE [OldDB];

ALTER DATABASE OldDB MODIFY FILE (NAME = OldDB, FILENAME = 'C:\...\NewDB.mdf');

ALTER DATABASE OldDB MODIFY FILE (NAME = OldDB_log, FILENAME = 'C:\...\NewDB_log.ldf');

ALTER DATABASE MyDB MODIFY FILE (NAME = OldDB, NEWNAME = NewDB);

ALTER DATABASE MyDB MODIFY FILE (NAME = OldDB_log, NEWNAME = NewDB_log);

Now take the database offline and then bring it online again.

Rename the .mdf and .ldf file on the disk.

Finally rename the DB by just clicking into the name and change it. This only works when there are no connections to the database and if the database is online.

 

Leave a Reply

Your email address will not be published. Required fields are marked *