SET NOCOUNT ON
GO
DECLARE @dbName NVARCHAR (255);
DECLARE @SqlStatement NVARCHAR(4000);
DECLARE databaseCurs CURSOR FOR
SELECT name FROM sys.databases WITH (NOLOCK)
WHERE name NOT IN ('tempdb','model', 'master', 'msdb')
OPTION (RECOMPILE);
OPEN databaseCurs;
FETCH NEXT FROM databaseCurs INTO @dbName
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
SET @SqlStatement = N'ALTER DATABASE [' + @dbName + N']' + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE; ' + N'DROP DATABASE [' + @dbName + N'];';
----SET @SqlStatement = N'BACKUP LOG [' + @dbName + N'] TO DISK = ''S:\BACKUP\' + @dbName + N'.BAK'''; (For Transaction Log Backup)
EXECUTE sp_executesql @SqlStatement
--print @SqlStatement
PRINT N'drop database completed suceessfully: ' + @dbName
END;
FETCH NEXT FROM databaseCurs INTO @dbName;
END;
CLOSE databaseCurs;
DEALLOCATE databaseCurs;
GO