Posted On September 3, 2020

SQL: Backup Database and Purge It From SQL Server

kimconnect 0 comments
blog.KimConnect.com >> Database >> SQL: Backup Database and Purge It From SQL Server
/* Make a Final Backup of Database, Purge Its Backup and Restore History, and Remove Database */

/* Make a Final Backup */
BACKUP DATABASE DATABASE_NAME TO DISK = '\\ARCHIVE\Databases\DATABASENAME.bak' WITH COMPRESSION
GO

/* Purge Backup Chain Metadata */
EXEC msdb.dbo.sp_delete_database_backuphistory @database_name = N'DATABASENAME'
GO

/* Set Exclusive Access of SQL Server Database before Dropping It  */
/* Preempt this error:
Drop failed for Database 'DATABASENAME'. (Microsoft.SqlServer.Smo)
Cannot drop database "DATABASENAME" because it is currently in use. (Microsoft SQL Server, Error: 3702)
Cannot drop database because it is currently in use Microsoft SQL Server Error 3702
*/
USE [master]
GO
ALTER DATABASE [DATABASENAME] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE [DATABASENAME] -- Now Delete the Database
GO

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

Microsoft SQL Server: How to Use T SQL to Move Transaction Log Files

Automated Script: # moveDbStorage.ps1 # Version 0.0.1 # This version is intended for a local…

SQL Server Overview

SQL Buffer Manager (Cache) 8K Pages between memory and disk storage 8 Pages = 1…

Use PowerShell to Set Microsoft SQL Database Owner

$owner='CAP\SQL Admins' $databaseName='TestDb' $sqlServer=$env:computername function setDbOwner{ param( $principle=$env:USERDOMAIN+'\Domain Admins', $databaseName='TestDB', $sqlServer ) function includeSqlTools{ $ErrorActionPreference='stop'…