20110221

Disconnecting users from MSSQL database

When trying to restore database from backup often error saying about connected users is displayed.
Script below kills all connections to given database.
Just replace XYZ with required database name.
Remember that all connections will be dropped without notice.

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('XYZ')    
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      

1 comment:

Anonymous said...

Or you could just put database into single user mode