Wednesday, June 8, 2011

Kill All MSSQL Database Sessions

This will disconnect all users from a specific MSSQL database. Replace YOURDBNAME with your database name. Thanks to http://adammatusiak.blogspot.com/2011/02/disconnecting-users-from-mssql-database.html


USE master

GO

DECLARE @userId varchar(10)

DECLARE cur CURSOR READ_ONLY
FOR
SELECT request_session_id
FROM master.sys.dm_tran_locks
WHERE resource_type = 'DATABASE'
AND resource_database_id = db_id('YOURDBNAME')
GROUP BY request_session_id

OPEN cur

FETCH NEXT FROM cur INTO @userId
WHILE (@@fetch_status <> -1)
BEGIN
IF (@@fetch_status <> -2)
BEGIN
PRINT 'Killing connection ' + @userId
EXEC ('KILL ' + @userId)
END
FETCH NEXT FROM cur INTO @userId
END

CLOSE cur
DEALLOCATE cur

No comments: