I have Sql server data files saved on external storage. I want to detach specific database. If external storage is not connected I want to drop database.
Is this safe way to do that:
DECLARE @DB_NAME SYSNAME = 'Database_name';
BEGIN TRY
-- Check if db has correct structure
DBCC CHECKDB (@DB_NAME) WITH ALL_ERRORMSGS ;
-- Stop using db
EXEC( 'ALTER DATABASE ' +@DB_NAME + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ');
-- Detach db
EXEC sp_detach_db @dbname= @DB_NAME , @skipchecks= 'true';
END TRY
BEGIN CATCH
-- DB files are missing - drop database
IF ERROR_NUMBER() = 945
BEGIN
EXEC ('DROP DATABASE ' + @DB_NAME);
END
END CATCH;
sys.databasewill still "think" that everything is OK. – Hacko Mar 6 '12 at 9:19