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' ...

Get SQL Server 2014 with PowerShell v5 Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.