You may have faced situations when you need to restore a SQL Server database, but the restoration fails because a connected user prevents SQL Server from acquiring the required exclusive mode.
The T-SQL script below will kill all active sessions by switching immediately to exclusive mode. you’ll then be able to restore the db (or perform any other operation requiring exclusive mode), before switching back to multi-user mode.
[code lang=SQL]
USE master;
GO
ALTER DATABASE [YOUR_DB_NAME]
SET SINGLE_USER
WITH ROLLBACK IMMEDIATE;
GO
— Do your stuff. Ex : restore db
ALTER DATABASE [YOUR_DB_NAME]
SET MULTI_USER;
GO
[/code]
If you’re using the SQL Server Wizard to restore the db, you’ll have to switch back to multi_user mode before starting the restore (because of the exclusive mode). Unfortunately, this means that a client could once again open a connection between the switch to multi_user mode and the beginning of the restore.