views:

101

answers:

2

Hi,

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!

+2  A: 

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.

Joe Lloyd
@Joe - Thanks a lot for the quick and accurate response! Do you have a comment for or against using a try... catch block?
Ev
They do the same basic task, but TRY/CATCH statements generally have a few advantages if you're using SQL Server 2005 and onwards. You can still get at the error details with functions like error_message(), so if you have the option I'd say stick with TRY/CATCH as a rule.
Joe Lloyd
+5  A: 

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
KenJ
@kenJ - i've not seen a try catch block in SQL before but I really like it. Thanks for the answer!
Ev