Drop all databases from server
You can do this through the SSMS GUI. Select the Databases
node then F7 to bring up Object Explorer Details, Select all databases that you want to delete, Hit "Delete" and select the "Close Existing Connections" and "Continue after error" options.
Alternatively through TSQL you can do
EXEC sp_MSforeachdb '
IF DB_ID(''?'') > 4
BEGIN
EXEC(''
ALTER DATABASE [?] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DROP DATABASE [?]
'')
END'
And here is my solution for the same problem:
-- drops all user databases
DECLARE @command nvarchar(max)
SET @command = ''
SELECT @command = @command
+ 'ALTER DATABASE [' + [name] + '] SET single_user with rollback immediate;'+CHAR(13)+CHAR(10)
+ 'DROP DATABASE [' + [name] +'];'+CHAR(13)+CHAR(10)
FROM [master].[sys].[databases]
where [name] not in ( 'master', 'model', 'msdb', 'tempdb');
SELECT @command
EXECUTE sp_executesql @command
This will kill all connections, and delete all databases not in the list:
('master' ,'tempdb' ,'model' ,'msdb' ,'ReportServer' ,'ReportServerTempDB')
use [master]
DECLARE
@DATABASENAME nVARCHAR(20)
DECLARE
@TABLE TABLE
(NAME nVARCHAR(50))
Declare @SQL nvarchar(100)
INSERT INTO @TABLE
SELECT
name
FROM sys.databases
WHERE name not in
('master'
,'tempdb'
,'model'
,'msdb'
,'ReportServer'
,'ReportServerTempDB')
while (select COUNT(*) from @table) > 0
begin
select @DATABASENAME = (select top 1 (name) from @TABLE)
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE dbid = db_id(@DATABASENAME)
EXEC(@kill);
set @SQL = 'drop database ' + @DATABASENAME
exec sp_executesql @SQL, N'@databasename nvarchar(50)', @databasename;
print @databasename + ' has been deleted'
delete from @TABLE where NAME = @DATABASENAME
end