Thursday, November 3, 2011

How to kill open transactions in SQL Server

USE master
GO

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


SET @DBName = 'Testing'
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

2 comments:

Anuj Rathi said...

hi, this is really nice post. But I have an advice dear. Don't use your working database names in any post. I don't know that you know or not but some people did the same job & then ......

I think you can understand.
Best of luck !!

Sushil Rout (Sr SQL Server DBA) said...

Thanks a ton. I know all these things but i will remain cautious while writing articles.

Thank you.