You could write a dynamic SQL to do this:
use master
go
declare @dbnames nvarchar(max)
declare @statement nvarchar(max)
declare @closeconnection nvarchar(max)
set @dbnames = ''
set @statement = ''
select @dbnames = @dbnames + ',[' + name + ']' from sys.databases where name like 'zzz%'
if len(@dbnames) = 0
begin
print 'no databases to drop'
end
else
BEGIN
SET @closeconnection = 'alter database ' + substring(@dbnames, 2, len(@dbnames))
+ ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE'
set @statement = 'drop database ' + substring(@dbnames, 2, len(@dbnames))
print @statement
EXEC sp_executesql @closeconnection;
exec sp_executesql @statement;
end
Normally, the syntax to close all active connections to a database is:
--set it to single user to disable any other connections
ALTER DATABASE YourDatabase SET SINGLE_USER WITH ROLLBACK IMMEDIATE
--do your stuff here
--set it back to multiple users
ALTER DATABASE YourDatabase SET MULTI_USER
Alternatively, you could also generate a dynamic select list that populates your drop database statement along with close connection statements like this:
USE master;
Go
SELECT 'DROP DATABASE '+ name,
'alter database ' + name + ' SET SINGLE_USER WITH ROLLBACK IMMEDIATE'
FROM sys.databases WHERE name like 'zzz%';
GO
Courtesy: @SeriousM and OFH