I need to rename the filenames of a database because it did not fit in with our naming policy.
You have to detach and attach the database to rename the files – because they are open files locked by SQL server – this means the database has to be taken down for a short period.
Use the following SQL commands to achieve the rename:
Database: Testdatabase
DB Location: d:mssqldata
DB log location: e:mssqllogs
DB file name: Testdatabase.mdf
DB log file name: Testdatabase_log.ldf
New DB file name: renamedTestdatabase.mdf
New DB log file name: renamedTestdatabase_log.ldf
1. First detach the database:
EXEC sp_detach_db ‘Testdatabase’, ‘true’
2. Then rename the files – using command prompt/file explorer.
3. Lastly reattach the database:
EXEC sp_attach_db @dbname = N’Testdatabase’, @filename1 = N’d:mssqldatarenamedTestdatabase.mdf’, @filename2 = N’e:mssqllogsrenamedTestdatabase_log.ldf’