Skip to content

Instantly share code, notes, and snippets.

@DoubleBrotherProgrammer
Created January 4, 2011 03:12
Show Gist options
  • Save DoubleBrotherProgrammer/764335 to your computer and use it in GitHub Desktop.
Save DoubleBrotherProgrammer/764335 to your computer and use it in GitHub Desktop.
Kill all user sessions in SQL server
-- init vars
DECLARE @sessID int,
@dbName varchar(50),
@userName varchar(50)
SET @dbName = 'DA413' -- your database name
SET @userName = 'DA413' -- sql user account to look for
-- use a cursor to store all session_ids
DECLARE session_cursor CURSOR
FOR
SELECT session_id
FROM sys.dm_exec_sessions
WHERE original_login_name = @userName
-- open cursor and grab first row
OPEN session_cursor
FETCH NEXT FROM session_cursor INTO @sessID
-- loop through session_ids
WHILE @@FETCH_STATUS = 0
BEGIN
-- kill it
-- using EXEC because the sproc kill does not like @variables
EXEC('kill ' + @sessID)
-- get the next session_id
FETCH NEXT FROM session_cursor INTO @sessID
END
-- cursor cleanup
CLOSE session_cursor
DEALLOCATE session_cursor
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment