Delete All the databases from the Server, that Follow certain Pattern.

CREATE TABLE #databaseNames (name varchar(100) NOT NULL, db_size varchar(50), owner varchar(50), dbid int, created date, status text, compatibility_level int);
INSERT #databaseNames
exec sp_helpdb;

select * from #databaseNames

delete from #databaseNames where name not like ‘%upload%’

select * from #databaseNames

DECLARE dropCur CURSOR FOR
SELECT name FROM #databaseNames WHERE name like ‘%upload%’;
OPEN dropCur;
DECLARE @dbName nvarchar(100);
FETCH NEXT FROM dropCur INTO @dbName;
DECLARE @statement nvarchar(200);
WHILE @@FETCH_STATUS = 0
BEGIN
SET @statement = ‘DROP DATABASE ‘ + @dbName;
EXEC sp_executesql @statement;
FETCH NEXT FROM dropCur INTO @dbName;
END
CLOSE dropCur;
DEALLOCATE dropCur;
DROP TABLE #databaseNames;

Leave a comment