Sunday, December 4, 2011

How to move SQL Server database files to different location


How to move SQL Server database files to different location

(Works for SQL 2005/2008)

In case you need to move database files (data or log) to new location one way to do it is to detach the database, move the files to location and attach it back

1)      Detach database: Detaching a database removes it from the instance of the Microsoft SQL Server Database Engine but leaves intact the database, with its data files and transaction log files. Following script can be used


USE [master]
GO
EXEC master.dbo.sp_detach_db @dbname = N'MyDatabase'
GO


2)      Move files to new location: You can manually copy the files but I prefer to use XCOPY. Here is how

xcopy "C:\DATA\MyDatabase_Data.mdf" "D:\DATA\MyDatabase_Data.mdf" /P

3)      Attach the database: Attaching a database places it in exactly the same state that it was in when it was detached. Here is how


USE master;
GO
CREATE DATABASE MyAdventureWorks
    ON (FILENAME = 'D:\DATA\MyDatabase_Data.mdf')
    FOR ATTACH;
GO

4)    Final step is to verify that files are where you expect them to be

SELECT name, physical_name AS CurrentLocation, state_desc
FROM sys.master_files
WHERE database_id = DB_ID(N'MyDatabase');

No comments:

Post a Comment