Detaching and Attaching a database in SQLSERVER

 

We do detach and attach a database to improve the Performance, to move the physical drive location of datafiles on the same server or to different server and due to space constraints.


Steps to Detach and Attach a database:

Step-1: Change the Restrict Access to Single mode

Right click on database (devdb) -> Properties -> Options -> modify the Restrict Access to Single mode -> Ok






Step-3: Right click on database (devdb) -> Tasks -> Detach -> select "Drop connections" and "Update Statistics" -> Ok



Step-4: Move the datafiles and logfiles from old location to the new location from OS level 

Old location: C:\Program Files\Microsoft SQL Server\MSSQL11.MSSQLSERVER\MSSQL\DATA

New location: D:\Datafiles\devdb


Step-5: Right click on Databases -> Attach -> select the datafile from new location.



Step-6: Validate the database attached and the file locations.





Manual Method using Script:

Step-1: Locate the database file location

sp_helpdb devdb


Step-2: Set the database to single mode

USE master 

GO

ALTER DATABASE devdb 

SET SINGLE_USER WITH ROLLBACK IMMEDIATE

GO


Step-3: Detach the database devdb 

USE master

GO

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

GO


Step-4: Reattach the database using the FOR ATTACH command

USE master

GO

CREATE DATABASE devdb ON

(FILENAME =N 'D:\Datafiles\devdb\devdb.mdf'),

(FILENAME =N 'D:\Datafiles\devdb\devdb_log.ldf' )

FOR ATTACH 

GO


Step-5: Validate the database attach and the file locations

sp_helpdb devdb


Note: When we move a database using the detach and attach, the drawback is you will use the users in the original database after we move the database to a new server. To resolve this issue we can use sproc "sp_change_users_login".


Example: Exec sp_change_users_login "Update_One', 'john','john'



Comments

Popular posts from this blog

Auditing in Oracle database

rs.stepDown() in MongoDB replication

Tuples in Python