Friday, August 10, 2007

Kill SQL Server connections by username

You can use following SQL Script to kill connections by a single user, make sure you set the username in @UName variable.

SET NOCOUNT ON
DECLARE @UName varchar(50)
DECLARE @spidstr varchar(8000)
DECLARE @ConnKilled smallint
SET @ConnKilled=0
SET @spidstr = ''
Set @UName = 'USERNAME'
SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE loginame=@UName
IF LEN(@spidstr) > 0
BEGIN
EXEC(@spidstr)
SELECT @ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE loginame=@UName
END

No comments: