I want to drop a database. I have used the following code, but to no avail.
public void DropDataBase(string DBName,SqlConnection scon)
{
try
{
First check the connected databases
SP_WHO
Second Disconnect your database
DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'your_database_name'
DECLARE @SQL varchar(max)
SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
--SELECT @SQL
EXEC(@SQL)
FINALLY DROP IT
drop database your_database
Someone connected to the database. Try to switch to another database and then, to drop it:
Try
SP_WHO
to see who connected
and KILL
if needed
First make your data base offline after that detach it e.g.
Use Master
GO
ALTER DATABASE dbname SET OFFLINE
GO
EXEC sp_detach_db 'dbname', 'true'
I wanted to call out that I used a script that is derived from two of the answers below.
Props to @Hitesh Mistry and @unruledboy
DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'[[[DatabaseName]]]'
DECLARE @SQL varchar(max)
SELECT @SQL = COALESCE(@SQL,'') + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId
EXEC(@SQL)
alter database [[[DatabaseName]]] set single_user with rollback immediate
DROP DATABASE [[[DatabaseName]]]
A brute force workaround could be:
Stop the SQL Server Service.
Delete the corresponding .mdf and .ldf files.
Start the SQL Server Service.
Connect with SSMS and delete the database.
You cannot drop a database currently being used however you can use sp_detach_db
stored procedure if you want to remove a database from the server without deleting the database files.