Simply to clarify, ths is not a real question, more outside assistance for individuals much like me who have been searching for a solution.
Lots of programs create temp tables and so on, however i was surprised when Team Foundation Server produced 80+ databases on my small test SQL Server. TFS did not install properly, and kindly left me to obvious up after it. Since each database were built with a naming convention, instead of remove each database manually, I appreciated using cursors and also have written things i view to become probably the most foolish bit of T-SQL ever:
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; DECLARE dropCur CURSOR FOR SELECT name FROM #databaseNames WHERE name like '_database_name_%'; 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;
It's understandable that using cursors such as this is most likely really harmful, and really should be utilized with extreme care. This labored for me personally, and that i haven't seen any more harm to my database yet, however i disclaim: make use of this code at the own risk, and support your vital data first!
Also, if this ought to be erased since it is not really a question, I realize. Wanted to publish this somewhere people would look.
Why don't you simply do this rather?
USE master Go Choose 'DROP DATABASE '+ title FROM sys.databases WHERE title like '_database_title_%' GO
Capture the creation of that resultset after which paste it into another query window. Then run that. Why write all of this TSQL cursor code?
"If you have a hammer, everything appears like a nail!"..
this really is easy...
use master go declare @dbnames nvarchar(max) declare @statement nvarchar(max) set @dbnames = '' set @statement = '' select @dbnames = @dbnames + ',[' + name + ']' from sys.databases where name like 'name.of.db%' if len(@dbnames) = 1 begin print 'no databases to drop' end else begin set @statement = 'drop database ' + substring(@dbnames, 2, len(@dbnames)) print @statement exec sp_executesql @statement end