Monday, 18 October 2021

How to move SQL database files to a different location

Sometimes when SQL database files (.mdf and .ldf files) grow too large, the easiest solution might be to move them to a different location so we can free up disk space quickly.

Here are the steps to move these files:

1. Turn off all services or processes that are using the database

2. Note down the file locations of the .mdf and ldf files (by default, they are located at SQL Server application directory e.g., \\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA

3. Launch SQL Management Studio

4. Login and access the SQL server instance has the database

5. Click and highlight the database

6. Open Query Editor

7. Run following SQL script (please change the database name and location to suit)

1
2
3
4
5
6
7
8
9
ALTER DATABASE AdventureWorks2014  
    MODIFY FILE ( NAME = AdventureWorks2014_Data,  
                  FILENAME = 'E:\New_location\AdventureWorks2014_Data.mdf');  
GO
 
ALTER DATABASE AdventureWorks2014  
    MODIFY FILE ( NAME = AdventureWorks2014_Log,  
                  FILENAME = 'E:\New_location\AdventureWorks2014_Log.ldf');  
GO

8. Run following SQL script to set the database to be offline

1
2
ALTER DATABASE AdventureWorks2014 SET OFFLINE;  
GO
Note: if the database is too large and this statement may take a while to run. Or you can use the following statement instead.
1
2
ALTER DATABASE AdventureWorks2014 SET OFFLINE WITH ROLLBACK IMMEDIATE;  
GO

9. Browse to the files location (we noted down in Step 2) and move the files to the new location

10. In Query Editor, run following SQL script to bring the database online again

1
2
ALTER DATABASE AdventureWorks2014 SET ONLINE;  
GO
Note: if it fails with permission error, please change the user who runs the SQL services. You may do that by following the steps below via Services application.

1. Right click on the SQL Server service e.g., like the one highlighted in the screen shot below

2. Choose Properties option
3. Click Log On tab to change to the ideal user as required

OR

You may also grant access permission to the SQL Server service user on the new folder, where the database files are.


11. You may verify if the database is made online successfully by running the following statement

1
2
3
4
SELECT name, physical_name AS NewLocation, state_desc AS OnlineStatus
FROM sys.master_files  
WHERE database_id = DB_ID(N'AdventureWorks2014')  
GO

This article is originally sourced from this one and you may find more details there. Thank you. 

No comments: