How do I drop connections and detach a database in SQL Server
Frequently when moving or modifying databases, they need to be detached. The problem with this is a database can’t be detached if there are active connections to it.
The following code snippet disconnects active sessions and detaches the database myDbName
USE master; GO ALTER DATABASE myDbName SET SINGLE_USER WITH ROLLBACK IMMEDIATE; GO EXEC sp_detach_db @dbname = 'myDbName', @skipchecks = 'true'; GO