Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop database only if Backup is successful

This might be an easy one for some one but I haven't found a simple solution yet.

I'm automating a larger process at the moment, and one step is to back up then drop the database, before recreating it from scratch.

I've got a script that will do the back up and drop as follows:

Use [Master]
BACKUP DATABASE [databaseName]
  TO DISK='D:\Backup\databaseName\20100122.bak'

ALTER DATABASE [databaseName] 
    SET SINGLE_USER 
    WITH ROLLBACK IMMEDIATE

DROP DATABASE [databaseName] 

but I'm worried that the DROP will happen even if the BACKUP fails.

How can I change the script so if the BACKUP fails, the DROP won't happen?

Thanks in advance!

like image 354
Ev. Avatar asked Dec 04 '25 10:12

Ev.


1 Answers

If your SQL Server version is 2005 or greater, you can wrap your statements with a try catch. If the backup fails, it will jump to the catch without dropping the database...

Use [Master]
BEGIN TRY

BACKUP DATABASE [databaseName]
  TO DISK='D:\Backup\databaseName\20100122.bak'

ALTER DATABASE [databaseName] 
    SET SINGLE_USER 
    WITH ROLLBACK IMMEDIATE

DROP DATABASE [databaseName] 
END TRY
BEGIN CATCH
PRINT 'Unable to backup and drop database'
END CATCH
like image 147
KenJ Avatar answered Dec 07 '25 03:12

KenJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!