Move Database Files By SQL Script
1) Get database files details.
SELECT name, physical_name AS NewLocation, state_desc AS OnlineStatus FROM sys.master_files WHERE database_id = DB_ID(N'TestDatabase') GO
2) Run the following SQL script to set a new location for SQL database files.
ALTER DATABASE TestDatabase
MODIFY FILE ( NAME = TestDatabase,
FILENAME = 'C:\MSSQLDB\MSSQL15.MSSQLNODE1INST1\UserDB\Data\TestDatabase.mdf');
GO
ALTER DATABASE TestDatabase
MODIFY FILE ( NAME = TestDatabase_log,
FILENAME = 'C:\MSSQLDB\MSSQL15.MSSQLNODE1INST1\UserDB\Log\TestDatabase_log.ldf');
GO
3) Run the following SQL script to take SQL database offline:
ALTER DATABASE TestDatabase SET OFFLINE; GO |
4) Move mdf and ldf files to the new location specified in the statement of step2.
5) Now database can be set online by running the following query.
ALTER DATABASE TestDatabase SET ONLINE; GO
6) To verify the results by running the following query.
SELECT name, physical_name AS NewLocation, state_desc AS OnlineStatus FROM sys.master_files WHERE database_id = DB_ID(N'TestDatabase') GO

Move Database Files By using Detach and Attach Function
- Launch SSMS.
- Login to the SQL instance with an account that has the SysAdmin server role.
- Navigate to “Databases“.
- Right click the database that files to be moved to new location.
- Select “Properties“.
- In the Properties window, in the Select a Page panel, click “Files“.
- Record down the paths and filenames for the database.
- Click “OK”.
- Right click the same database again.
- Select “Tasks “, then click “Detach“.
- In the Detach Database window, check the box “Drop Connections“.
- Click “OK“.
- Launch Windows Explorer.
- Browse to the path recorded in step 7.
- Move the database’s files to the new location.
- Record down the paths where you have just moved the files to.
- Return to SSMS again.
- Right click “Databases“
- Select “Attach“.
- In the Attach Databases window, click “Add“.
- Browse to the path you wrote down in step 16.
- Select the .mdf filename for the database.
- Click “OK”.
- If the other files are not found, click the ellipsis next to the filename that is not found.
- In the Locate Database Files window, “browse” to the location of the file for the database that you wrote down in step 16.
- Select the file.
- Click “OK”.
- In the Attach Databases window, click “OK”.