I want to drop a database. I have used the following code, but to no avail.
public void DropDataBase(string DBName,SqlConnection scon)
{
try
{
If your dropping the database in SQL Management Studio and you get the message, don't forget that you use Master as selected database otherwise your query is also an connection to the database.
USE Master;
GO
DROP DATABASE AdventureWorks;
GO
In SQL Server Management Studio 2016, perform the following:
Right click on database
Click delete
Check close existing connections
Perform delete operation
before dropping a database, you drop the connection to that database first.
I have found a solution at http://www.kodyaz.com/articles/kill-all-processes-of-a-database.aspx
DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'YOUR_DABASE_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)
For SQL server mgmt. studio:
Right click database: Properties -> Options -> Restrict Access : Set to "Single User" and perform the drop afterwards
Go to available databases section and select master. Then Try DROP DATABASE the_DB_name.
select * from sys.sysprocesses where dbid = DB_ID('Test')
(Replace 'Test' with the name of the database you are trying to drop) This will tell you which processes are using it.
If you still want to force drop then, the ultimate approach is:
USE master;
GO
ALTER DATABASE Test
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
DROP DATABASE Test;
Hope this helps !