Occasionally, you may need to move a database file(s) to a new location in some cases like below but not limited to:
- The disk doesn't have enough free space to expand the database file.
- The disk needs to replaced with a new one.
- The disk hosts several database files so as to move some database files to other location to separate IO workloads.
Once the new disk is ready to use (SQL Server can see it), we can use the following steps to perform the change:
- Bring the database whose database file(s) needs to be move online.
- In the Windows file system, physically move database file(s) to the new location.
- Make sure the SQL Server service account has FULL CONTROL permission on the destination folder which contains the moved database file(s). If not, grant it.
- Update the new database file location(s) in the master database.
- Bring the database online.
The above steps apply to SQL Server 2005 and later versions, and database doesn't use File Stream or File Table features which needs more care. Here is an example based on AdventureWorks2008R2 database in SQL Server 2008 R2:
use master;
go
-- get the current databas file physical path
SELECT name AS database_file_logical_name, physical_name AS current_path, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'AdventureWorks2008R2');
go
-- set the databse offline before physically moving the file to the new path
alter database [AdventureWorks2008R2] set offline;
go
-- for each database file that needs to be moved, do
-- 1: physically move the databse file to the new path;
-- 2: make sure SQL Server service account has FULL CONTROL permission on the desctination folder
-- 3: run the following query to update the new path in master database
alter database [AdventureWorks2008R2] modify file (name = 'AdventureWorks2008R2_Data', filename = 'D:\SQL-Workspace\BDs\AdventureWorks2008R2_Data.mdf');
go
/*
-- for test purpose only - move it back to the original path
alter database [AdventureWorks2008R2] modify file (name = 'AdventureWorks2008R2_Data', filename = 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQL2008R2\MSSQL\DATA\AdventureWorks2008R2_Data.mdf');
go
*/
-- after all files moved, bring the database online
alter database [AdventureWorks2008R2] set online;
go
-- verify the database files are located in the new path
SELECT name AS database_file_logical_name, physical_name AS current_path, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'AdventureWorks2008R2');
go
Hope this helps :-)