I got a request this week from an application engineer. The request was to move ALL physical database files from one physical drive to another physical drive on the same machine.
Hmmmm, I have never moved ALL .mdf files from one place to another at one time. One of my teammates told the application engineer that it may take some time. He want to detach/move/attach all the DBs.
I knew this wouldn’t work because:
1) it would take forever
2) how are you going to detach the master DB?
So my solution contained 3 parts:
- Change the location of all the files inside SQL
- shutdown and move the files
- Change SQL’s startup parameters for the master database
Easy as Ï€.
I used some good old dynamic SQL to create an ALTER DATABASE script for each db (except the master)
--first, let's just take a look and see where our files are living SELECT name, physical_name, CASE WHEN TYPE = 0 THEN 'DATA' WHEN TYPE = 1 THEN 'LOG' END AS FileType FROM sys.master_Files --Now let's create those ALTER DB statements SELECT 'Alter DATABASE ' + d.name + ' MODIFY FILE ( NAME = ' + f.name + ', FILENAME = ' + --here is where you want to put where you want to move your files ' ''c:\NewFolder\'+ right(physical_name, charindex('\',reverse(physical_name))-1 ) + ''' ) ' FROM sys.databases d inner join sys.master_files f on d.database_id = f.database_id where --remove this if you want both DB AND log file type = 0 --and keep this part, dbid 1 is master and d.database_id <> 1 --Check again to see if the physical name is changed select name, physical_name, case when type = 0 then 'DATA' when type = 1 then 'LOG' end as FileType from sys.master_Files
After you run this, you should see this message a bunch of times:
The file “tempdev” has been modified in the system catalog. The new path will be used the next time the database is started.
Now you can shut down your SQL services and move the physical files to their new location.
Once you have all the files moved over (including the master) you’ll need to change the startup parameters.
To do this:
- open up the configuration manager
- Right click on your SQL instance –> properties
- Click on advanced –> startup parameters
- Change the location of the master .mdf