I am trying to detach a local database, but getting errors because there are existing connections to it.
How do I close existing connections on my local database?
PS. Running on SQL Server 2008 Express
To disconnect the connection after the query completes, from the menus go to Tools > Options > Query Execution > SQL Server > Advanced and select "Disconnect after the query executes". By checking this option, after the query executes the database connection will be disconnected.
In SQL Server Management Studio Object Explorer, connect to the instance of the SQL Server Database Engine and then expand the instance. Expand Databases, and select the name of the user database you want to detach. Right-click the database name, point to Tasks, and then select Detach.
Take it offline first. THe dialog for that allows a force option. Then you can detach it safely.
Disconnect All the Other Users to Your Database
ALTER DATABASE [YourDbName]
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
Disconnect your SSMS Connections to Database
If you are the only User connected to a database and want to disconnect all the connection made by you in SSMS you can goto any of the Query windows
open on SSMS and Right Click and see below:
Manually (and thus, with a bit of effort, programmatically) you can use the KILL
command to summarily close open connections to the database.
Identifying which conenctions to close, now that's the hard part. Start with system procedures SP_WHO
and SP_WHO2
to manually identify what connections are using which databases; use and analysis of these procedures may lead to referencing system objects sys.processes, sys.dm_exec_sessions, and a host of others, followed by an eventual understanding of SPIDs and an inevitable respectful loathing of connection pools.
All of these are covered in detail in SQL Books Online. It's the beginning of a pretty extensive maze, and how far you get into it depends on your ultimate goals and objectives.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With