Kill Open Database Processes

When a database has open connections left, and that happens a lot, you can kill them by using the script below after replacing $DBNAME$ with your database name.

DECLARE @DatabaseName nvarchar(50)
SET @DatabaseName = N'$DBNAME$'

DECLARE @SQL varchar(max)
SET @SQL = ''

SELECT @SQL = @SQL + 'Kill ' + Convert(varchar, SPId) + ';'
FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId


This is very useful when trying to execute functions take offline, restore and other similar ones.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s