Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK) Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK) sql sql

Script to kill all connections to a database (More than RESTRICTED_USER ROLLBACK)


Updated

For MS SQL Server 2012 and above

USE [master];DECLARE @kill varchar(8000) = '';  SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), session_id) + ';'  FROM sys.dm_exec_sessionsWHERE database_id  = db_id('MyDB')EXEC(@kill);

For MS SQL Server 2000, 2005, 2008

USE master;DECLARE @kill varchar(8000); SET @kill = '';  SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'  FROM master..sysprocesses  WHERE dbid = db_id('MyDB')EXEC(@kill); 


You can get the script that SSMS provides by doing the following:

  1. Right-click on a database in SSMS and choose delete
  2. In the dialog, check the checkbox for "Close existing connections."
  3. Click the Script button at the top of the dialog.

The script will look something like this:

USE [master]GOALTER DATABASE [YourDatabaseName] SET  SINGLE_USER WITH ROLLBACK IMMEDIATEGOUSE [master]GODROP DATABASE [YourDatabaseName]GO