Last updated on December 7th, 2016 at 04:08 pm

Sometimes you roll out a database and later decide that the name you picked isn’t what you really want. To rename a SQL database and it’s associated files, use the Detach and Attach functions. Let’s say the original database was named “MyStupidDatabase” and used files C:\MyStupidDatabase.mdf and C:\MyStupidDatabase.ldf. We want to rename the database and it’s associated files to “MyFreakingAwesomeDatabase”.

Detach Database

To detach the database, use the sp_detach_db stored procedure:

After detaching the database, rename MyStupidDatabase.mdf to MyFreakingAwesomeDatabase.mdf and MyStupidDatabase.ldf to MyFreakingAwesomeDatabase.ldf.

Attach Database

Once you’ve renamed your database and log files, it’s time to attach the database with the sp_attach_db stored procedure: