How To Attach and Detach a Database in SQL Server

How To Attach and Detach a Database in SQL Server

In this tutorial i will let you know that how can you attach or detach  SQL Server database in Sql server. How to attach and detach a database in SQL Server is very easy. You just have to follow few simple steps. By this we can move our database from one server to another and attach them for testing purpose. But there must compatibility issues when server version is different.

For this we start from that how can we make a database.If you are new in SQL Server then you will find this here.After creating the database right click on the database which you want to detach.

Right click on database > Click on Task > Click on Detach.

This will detach your database.To Attach the database right click on Databases >click on Attach > Locate your .mdf file and attach it.

Script:-

USE master
GO
----Detach the database--------

exec master.dbo.sp_detach_db @dbname =N'campus'
GO
---ATTACH THE DATABASE---------

EXEC MASTER.DBO.sp_attach_db @DBNAME =N'CAMPUS',
@FILENAME1=N'C:\Program Files\SQL\MSSQL10\MSSQL\DATA\CAMPUS.MDF',
@FILENAME2=N'C:\Program Files\SQL\MSSQL10\MSSQL\DATA\CAMPUS_1.LDF'
GO

Video Guide:-