How to Move Database Files in MSSQL: A Step-by-Step Guide

Move the MDF and LDF files to another directory.
Update DatabaseName and Directories using the commands below.

  • Switch to the master database
USE master;
GO
  • Put the database in offline mode
ALTER DATABASE DatabaseName SET OFFLINE WITH ROLLBACK IMMEDIATE;
  • Copy files to the desired directory modify and run the below command
ALTER DATABASE DatabaseName
MODIFY FILE (NAME = data, FILENAME = 'D:\Database\DATABASE.mdf');
ALTER DATABASE {DatabaseName}
MODIFY FILE (NAME = log, FILENAME = 'D:\Data\DATABASELOG.ldf');
SELECT name, physical_name
  • Verify the changes
FROM sys.master_files
WHERE database_id = DB_ID('DatabaseName');
  • Bring database online
ALTER DATABASE DatabaseName SET ONLINE;

Leave a Reply