Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Move SQL Server 2008 database files to a new folder location

Logical Name

  • my_Data
  • my_Log

Path:

  • C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA
  • C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQLSERVER\MSSQL\DATA

FileName:

  • my.MDF
  • my_1.LDF

What would be the sql script to move these files to a new location: D:\DATA

Database is live so I would need to close existing connections.

like image 466
FiveTools Avatar asked Jul 05 '11 15:07

FiveTools


People also ask

How do I move files from one drive to another drive in SQL Server?

In SQL Server, you can move system and user databases by specifying the new file location in the FILENAME clause of the ALTER DATABASE statement. Data, log, and full-text catalog files can be moved in this way. This may be useful in the following situations: Failure recovery.

How do I move a database file in SQL Server?

Right-click the instance and select Properties. In the Server Properties dialog box, select Database Settings. Under Database Default Locations, browse to the new location for both the data and log files. Stop and start the SQL Server service to complete the change.


Video Answer


1 Answers

You forgot to mention the name of your database (is it "my"?).

ALTER DATABASE my SET SINGLE_USER WITH ROLLBACK IMMEDIATE;  ALTER DATABASE my SET OFFLINE;  ALTER DATABASE my MODIFY FILE  (    Name = my_Data,    Filename = 'D:\DATA\my.MDF' );  ALTER DATABASE my MODIFY FILE  (    Name = my_Log,     Filename = 'D:\DATA\my_1.LDF' ); 

Now here you must manually move the files from their current location to D:\Data\ (and remember to rename them manually if you changed them in the MODIFY FILE command) ... then you can bring the database back online:

ALTER DATABASE my SET ONLINE;  ALTER DATABASE my SET MULTI_USER; 

This assumes that the SQL Server service account has sufficient privileges on the D:\Data\ folder. If not you will receive errors at the SET ONLINE command.

like image 72
Aaron Bertrand Avatar answered Sep 28 '22 07:09

Aaron Bertrand