How to Detach and Attach Database in SQL Server

Following way we can detach and Attach Database in SQL Server:
1. Using SQL Server Management Studio (GUI)
2. Using T-SQL

1. Using SQL Server Management Studio (GUI)







Using T-SQL Script:

--Detach Script
USE [master]
GO
ALTER DATABASE [Sales] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO

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

--Attach Script
USE [master]
GO
CREATE DATABASE [Sales] ON ( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER01\MSSQL\DATA\Sales.mdf' ),
( FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER01\MSSQL\DATA\Sales.ldf' )
FOR ATTACH
GO



Comments