How to Attach and Detach Databases - SQL Server DBA Tutorial

In this video you will learn how to attach and detach databases using SQL Server Management Studio as well as using T-SQL script. After watching this video, you will also learn real time scenarios where it would be a good practice to attach and detach databases. 

Scripts used in this video

--Attach Script
USE [master]
GO

CREATE DATABASE [TestDB] ON ( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.SQLPROD\MSSQL\DATA\TestDB.mdf' ),
( 
FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL12.SQLPROD\MSSQL\DATA\TestDB_log.ldf' )
FOR ATTACH
GO


--Detach Script
USE [master]
GO

ALTER DATABASE [SalesOrders] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

USE [master]
GO

EXEC MASTER.dbo.sp_detach_db @dbname = N'SalesOrders'
GO

 
 
 
How to Attach and Detach Database in SQL Server