Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop all databases from server

I have a server (SQL Server 2005) with more than 300 databases. I don't want to right-click one by one and select Delete.

How can I delete all databases easily?

like image 452
Moslem7026 Avatar asked Apr 25 '11 10:04

Moslem7026


People also ask

How do I drop all databases?

First list all databases on your server. Use the command 'SHOW DATABASES;' in the mysql-console like in the example above. Now copy the name of the database you want to delete. To do delete a database you need the command 'DROP DATABASE'.

How do I drop multiple databases in SQL Server?

If you want to drop multiple databases using a single statement, you can use a comma-separated list of database names after the DROP DATABASE clause. The IF EXISTS option is available from SQL Server 2016 (13. x). It allows you to conditionally delete a database only if the database already exists.

How do I force a database to drop in SQL Server?

To remove a database from the current server without deleting the files from the file system, use sp_detach_db. USE master; ALTER DATABASE [databasename] SET SINGLE_USER WITH ROLLBACK IMMEDIATE; DROP DATABASE [databasename] ; Note, database backups will not be deleted as part of the process documented above.

Does drop database delete files?

Dropping a database deletes the database from an instance of SQL Server and deletes the physical disk files used by the database. If the database or any one of its files is offline when it is dropped, the disk files are not deleted. These files can be deleted manually by using Windows Explorer.


2 Answers

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' 
like image 98
Martin Smith Avatar answered Oct 02 '22 12:10

Martin Smith


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 
like image 34
Pellared Avatar answered Oct 02 '22 12:10

Pellared