How do I move SQL Server database files?

432    Asked by ChrisDyer in Salesforce , Asked on Jul 16, 2021

You don't have to stop the SQL Server service to move database files, but you do have to take the specific database offline. This is because you can't move files while they're being accessed and taking the database offline stops the files from being used by the SQL Server application. The process to move them is fairly simple. Detach/Attach was already described, but it is not nearly this complex. Change the file locations with an ALTER DATABASE command: USE master; --do this all from the master ALTER DATABASE foo MODIFY FILE (name='DB_Data1' ,filename='X:\\NewDBFile\\DB_Data1.mdf'); --Filename is new location Note, you do not need to declare the old location in this command. Changing this path does not take effect immediately, but will be used the next time the database starts up.Set the database offline (I use WITH ROLLBACK IMMEDIATE to kick everyone out and rollback all currently open transactions) ALTER DATABASE foo SET OFFLINE WITH ROLLBACK IMMEDIATE; Move/Copy the files to the new location Just copy the files over using your favorite method (Click 'n Drag, XCopy, Copy-Item, Robocopy) Bring the database online

ALTER DATABASE foo SET ONLINE;

Answered by Dylan Forsyth

  • To download sql server move database files you should check whether your MDF and LDF files are protected and cannot be moved while the database is online. If you don't mind stopping the database from working, then you can DETACH it, move the files and then ATTACH it.
  • Right click on the name of the database
  • Select Properties
  • Go to the Files tab
  • To download sql server move database files you should make a note of the Path and FileName of MDF and LDF files. This step is important in case you don't want to end up searching for missing files...
  • Right click on the database name
  • Select Tasks -> Detach
  • Move the files where you want
  • Right click on the Databases node of your server
  • Select Attach
  • Click on the Add button
  • Point to the new location
  • Click OK
  • You should be OK now. Info about the DETACH - ATTACH process can be found here. In the link about DETACH - ATTACH there is a recommendation of using ALTER DATABASE statement if keeping the database on the same instance of SQL Server. More reference in Move User Databases. If you want to keep it running while moving, then do a BACKUP - RESTORE. In the restore process you may define the new location of the database files. This will help you in sql server move database files.




Your Answer

Interviews

Parent Categories