Detaching and Attaching Database via scripts

We have all used SQL Server Management Studio to detach a database and attach them but have you every wondered what the SQL code is to execute this process directly in the query analyzer?

Detach:
USE [master]
GO
ALTER DATABASE [AdventureWorks] SET  SINGLE_USER WITH ROLLBACK IMMEDIATE
GO
USE [master]
GO
EXEC master.dbo.sp_detach_db @dbname = N’AdventureWorks’, @skipchecks = ‘false’
GO

Attach:
USE [master]
GO
CREATE DATABASE [AdventureWorks] ON
( FILENAME = N’C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQL2008\MSSQL\DATA\AdventureWorks_Data.mdf’ ),
( FILENAME = N’C:\Program Files\Microsoft SQL Server\MSSQL10.MSSQL2008\MSSQL\DATA\AdventureWorks_Log.ldf’ )
FOR ATTACH
GO

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s