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

T-SQL Msg 3101 Exclusive access could not be obtained because the database is in use

Symptom: Msg 3101, Level 16, State 1, Line 2Exclusive access could not be obtained because…

MS SQL: Using Profiler to Trace Failed Logins

Story: There has been an issue with a service account triggering login errors at the…

PowerShell: Optimize SQL Server Memory & CPU Resources

# optimizeSqlServer.ps1 # Version 0.0.2 # This version deals with Memory, CPU # Future versions…