While trying to restore SQL Server database or do any other actions which require exclusive database access you may face with the following error:
Exclusive access could not be obtained because the database is in use.
Here is a quick solution which is much handier than killing all connections manually from SSMS GUI. Before running the script below make sure that you`re not killing the connections of production users for example or affecting business in any other unwanted way. And don`t forget to put the name of your database to the script.
USE [master]
GO
DECLARE @dbname nvarchar(255)
DECLARE @spid int
DECLARE @command nvarchar(300)
/*-------------------------------------
-------Put your database name here ----
--------------------------------------*/
SET @dbname = 'Your database name here'
/*------------------------------------*/
DECLARE dbprocess CURSOR FAST_FORWARD FOR
SELECT sys.databases.name, sys.sysprocesses.spid
FROM sys.sysprocesses INNER JOIN
sys.databases ON sys.sysprocesses.dbid = sys.databases.database_id
WHERE (sys.databases.name = @dbname)
OPEN dbprocess
FETCH NEXT FROM dbprocess INTO @dbname, @spid
WHILE @@FETCH_STATUS = 0
BEGIN
SET @command = ' '
SET @command = 'Kill' +' '+ cast(@spid as nvarchar(5))
EXEC (@command)
FETCH NEXT FROM dbprocess INTO @dbname, @spid
END
CLOSE dbprocess
DEALLOCATE dbprocess
After running the script above you can proceed with the operation which required exclusive access to the database and now it will be successful.