Business Intelligence Blogs

View blogs by industry experts on topics such as SSAS, SSIS, SSRS, Power BI, Performance Tuning, Azure, Big Data and much more! You can also sign up to post your own business intelligence blog.

Kill them all... Your SPIDs of course!

  • 25 June 2012
  • Author: kylewalker
  • Number of views: 13479
  • 0 Comments

I had a pretty common task to perform the other day.  And that task was to simply restore a database on a development server.  Now, restoring a database in and of itself is a very simple thing to do.  So simple, it's probably one of the very first things you learn to do when learning SQL Server.  However, when you're learning SQL Server on your personal laptop or desktop, you don't have a number of other people connected to the database.  You may have others connected when in a work environment.

When you have other people working on a db, you've got other open connections to the database besides your own.  Typically, a way to close those connections is by using the "KILL" statement.  You can run an sp_who2 statement to find all of the open SPIDs and then run KILL (::SPID::) to close the connection.  Now the problem I ran into using this method, aside from being more time consuming and tedious, was that while I was running the kill statements on the list of SPIDs that I found, other connections were being opened.  So I received another error when attempting to restore the database.  The solution for this is pretty simple.  Just kill all of the connections at once and immediately attempt to restore the database.  So I found a script that did that very thing...

SET NOCOUNT ON
DECLARE @DBName varchar(50)
DECLARE @spidstr varchar(8000)
DECLARE @ConnKilled smallint
SET @ConnKilled=0
SET @spidstr = ''

Set @DBName = 'DATABASE_NAME'
IF db_id(@DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END
SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(@DBName)

IF LEN(@spidstr) > 0
BEGIN
EXEC(@spidstr)
SELECT @ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(@DBName)
END

I found this script here on stackoverflow.com.

This script will go through all of the SPIDs connected to the db that you enter as the "@DBName" parameter and kill the connection, leaving the db available to perform a restore.

 

Print
Tags:
Rate this article:
No rating

kylewalkerkylewalker

Other posts by kylewalker

Please login or register to post comments.