Solution for Exclusive access could not be obtained because the database is in use

Problem: When trying to restore database when in use, you might get the below exception.

Exception on SQL Server: Restore failed for Server '10.0.20.88'. (Microsoft.SqlServer.SmoExtended) System.Data.SqlClient.SqlError: Exclusive access could not be obtained because the database is in use. (Microsoft.SqlServer.Smo)

Solution:

To kill all the connections to your database you can use the ALTER DATABASE command. Sometimes you want to restore the database from a backup but can't because people are connected. Here is one way which will kick off all the users immediately.
Replace the below DataBaseName with the database name with you want to restore. -- Set your current Database connection to use MASTER otherwise you might get an error use master ALTER DATABASE DataBaseName SET SINGLE_USER WITH ROLLBACK IMMEDIATE --Alter the database to accept multi user connections ALTER DATABASE DataBaseName SET MULTI_USER Love coding!