Detaching a database
In this recipe, we will detach a database programmatically.
Getting ready
For the purpose of this recipe, let's create a database called TestDB
and put its data files in the C:\DATA
folder. Open up SQL Server Management Studio and run the following code:
IF DB_ID('TestDB') IS NOT NULL DROP DATABASE TestDB GO CREATE DATABASE [TestDB] CONTAINMENT = NONE ON PRIMARY ( NAME = N'TestDB', FILENAME = N'C:\DATA\TestDB.mdf' , SIZE = 4096KB , FILEGROWTH = 1024KB ), FILEGROUP [FG1] ( NAME = N'data1', FILENAME = N'C:\DATA\data1.ndf' , SIZE = 4096KB , FILEGROWTH = 1024KB ), FILEGROUP [FG2] ( NAME = N'data2', FILENAME = N'C:\DATA\data2.ndf' , SIZE = 4096KB , FILEGROWTH = 1024KB ) LOG ON ( NAME = N'TestDB_log', FILENAME = N'C:\DATA\TestDB_log.ldf' , SIZE = 1024KB , FILEGROWTH = 10%) GO
How to do it...
To detach a database programmatically, follow these steps:
Open PowerShell ISE as administrator.
Import the SQLPS module and create a new SMO Server object:
#import SQL Server module Import...