How to perform detach and attach a database in SQL Server DB

 How to perform detach and attach a database in SQL Server DB


sp_helpdb test

--Set the database to a single user mode

USE [master]
GO

ALTER DATABASE [test] 
SET SINGLE_USER WITH ROLLBACK IMMEDIATE
GO


--Detach the database using the sprocs


USE [master]
GO

EXEC master.dbo.sp_detach_db @dbname = N'test', @skipchecks = 'false'
GO

--Reattach the database using the FOR ATTACH command


USE [master]
GO
CREATE DATABASE [test] ON 
( FILENAME = N'E:\DataFiles\test.mdf' ),
( FILENAME = N'F:\LogFiles\test_log.ldf' )
 FOR ATTACH --<<use for attach to attach the sales database
GO

Note: when moving a database using detach and attach, you will lose the users in the original database after the completion of the move to a new server.  To resolve this, use the following sproc to link the user to the login in the new server.


EXEC sp_change_users_login 'user'


Comments