SQL-Server: Error - Exclusive access could not be obtained because the database is in use
I'll assume that if you're restoring a db, you don't care about any existing transactions on that db. Right? If so, this should work for you:
USE masterGOALTER DATABASE AdventureWorksDWSET SINGLE_USER--This rolls back all uncommitted transactions in the db.WITH ROLLBACK IMMEDIATEGORESTORE DATABASE AdventureWorksDWFROM ......GO
Now, one additional item to be aware. After you set the db into single user mode, someone else may attempt to connect to the db. If they succeed, you won't be able to proceed with your restore. It's a race! My suggestion is to run all three statements at once.
execute this query before restoring database:
alter database [YourDBName] set offline with rollback immediate
and this one after restoring:
alter database [YourDBName] set online