How to move or change data(.mdf) file or log(.ldf) file in SQL Server
Sometime we need to change database data (.mdf) and log(.ldf) file for maintenance purpose or server transfer purpose. There are two ways to do this.
Way 1: Using SQL Script
-- First get physical file path of data (.mdf) and log (.ldf)
-- set active database which you want to get file path, here in my case I am using Demo database
USE Demo
GO
-- This will give physical file path of current database
sp_helpfile
GO
-- Now, Set database to single user mode and detach database with disconnecting active sessions
Use MASTER
GO
-- Set database to single user mode
ALTER DATABASE demo SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
GO
-- Detach the database
sp_detach_db 'Demo'
GO
-- This will detach databse
EXEC SP_DETACH_DB @dbname = 'Demo', @skipchecks = 'true';
-- Now move .mdf or .ldf file on your preferred location
-- Attach database with log file at new location (Here I have moved log file only, if you want to mo
USE master
GO
-- Now Attach the database
sp_attach_DB 'Demo',
'C:\Program Files\Microsoft SQL Server\MSSQL14.MSSQLSERVER\MSSQL\DATA\Demo.mdf',
'C:\FolderName\SQL\Demo_log.ldf'
Way 2: Using SQL Management Studio user interface
1. Right click on database which you want to move data or log file
2. Select Detach option
3. Select checkbox for "Drop Connections" in opened window and then click OK button
4. Now move .mdf or .ldf file on your preferred location
5. Now you will not see your database in Object explorer
--- Attach database
6. Right click on database and select attach option
7. It will open a popup window
8. Click on "Add..." button in "Databases to attach"
9. It will open another popup to select database name which you want to attach, here now you have to select data (.mdf) file and click OK button
10. Now you will see database file location in first window popup, if it is not correct file location then select correct location
11. Finally click on "OK" button, and your database will be attached in couple of seconds.
Enjoy !!!
:)