简体   繁体   中英

Move SQL Server 2008 R2 database files to a new folder location

Currently i have a list of databases i wish to move on the current server.

DATA:

Current Path: Drive:\\MSSQL\\DATA\\FOLDER

New Path: Drive:\\MSSQL\\DATA

LOGS:

Current Path: Drive:\\MYSSQL\\LOGS\\FOLDER

New Path: Drive:\\MYSSQL\\LOGS

Is there a SQL script that can be used to set offline multiple databases, detactch them and attach them to the new location? This is also a production enviroment and are pretty large databases (a backup and restore would take much longer). In total 9 databases need to be moved, is this a simple procedure aslong as the location and user have required permissions? Thank you for any help.

This is a simple procedure, and you don't really need to detach the database to do it either, you can just do something along the lines of:

  • set db offline
  • alter the file location in the master db (using alter database)
  • physically move the files
  • set db online

The process is described in the following article:

Move User Databases

So long as the user moving the files has the permissions and the service account you're running SQL server as has full control of the new folder it's quite easy, and something I've done many times.

Doing it for multiple databases too is simple once you've worked out the procedure for doing the first one.

You can use this code to change the path. But you have to manually move the files to the new location. The WITH ROLLBACK IMMEDIATE speeds up the offline procedure by disconnecting any current connections.

ALTER DATABASE <db-name> SET OFFLINE WITH ROLLBACK IMMEDIATE;
ALTER DATABASE <db-name> MODIFY FILE ( NAME = <db-name>, FILENAME = <db-path\filename.mdf> );
ALTER DATABASE <db-name> SET ONLINE;

For more info check the relevant MSDN article

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM