Drop database only if Backup is successful
-
22-09-2019 - |
문제
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!
해결책
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
다른 팁
You can catch any error codes that occur with the SQL server error variable as follows. A zero indicates no error occurred. Note that the value is set every time a T-SQL statement is executed, so you need to catch it as soon as you have backed up:
USE [Master]
DECLARE @errorCode int
BACKUP DATABASE [databaseName]
TO DISK='D:\Backup\databaseName\20100122.bak'
SET @errorCode = @@ERROR
IF (@errorCode = 0)
BEGIN
ALTER DATABASE [databaseName]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE
DROP DATABASE [databaseName]
END
This is the simplest way I can think of, as well as allowing you to catch known error codes and handle them differently if you need to. SELECT * FROM master.sys.messages
gives you a list of all known error codes and messages if you want to take it further.