Renaming MS SQL 2005 database filenames

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’

Author: James

IT Manager - Network, Web coding, MS SQL and Online Mapping expert

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: