Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server

Move Database File from One Drive to Another Drive

5.00/5 (2 votes)
17 Oct 2018CPOL 5.5K  
Moving database file from one drive to another drive

Introduction

Sometimes, we need to change the database file location from one drive to another drive. Here are some simple tips on how we can achieve this goal.

Steps

  1. Suppose you have a database file named Test and you want to move it to other drive from the default location. First, run the following query to get information about the database file.
    SQL
    select * from Test.sys.database_files

    Using databse_files view, you can get information about databasefile such as Name, physical_name, state_desc. From physical_name column, you get the current location of the database file.

  2. Run database OFFLINE script:
    SQL
    use master
    alter database Test set OFFLINE
  3. Move database file (both .mdf, .ldf) to the desired location. In my case, I have moved my files in D drive SqlDatabase folder (D:\SqlDatabase).
  4. Update database and modify File. Set FileName as your desired location:
    SQL
    ALTER DATABASE test 
    MODIFY FILE (
        NAME = 'test',
        FILENAME = 'D:\SqlDatabase\Test.mdf'
    )
    
    ALTER DATABASE test
    MODIFY FILE (
        NAME = 'test_log',
        FILENAME = 'D:\SqlDatabase\Test_log.ldf'
    )
  5. Change the permission of these files and give full control to Users Group.

    Image 1

  6. Run database online script:
    SQL
    ALTER DATABASE Test SET ONLINE 

By following these simple steps, you can move your database from one drive to another.

Points of Interest

History

  • 18th October, 2018: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)