If a database is “in use” during attempted restore, you will get an error like the following:
Msg 3101, Level 16, State 1, Line 1
Exclusive access could not be obtained because the database is in use.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.
To solve the problem, write a restore SQL script and start it with a line like the following. *WARNING* this command will deny access to all users except the currently running script … MAKE SURE YOU KNOW WHAT YOU’RE DOING!! I usually run the script from an elevated “administrator” command-line using the “sqlcmd -i input_file” tool.
ALTER DATABASE [dbname] SET SINGLE_USER WITH ROLLBACK IMMEDIATE
If restoring a backup onto a different server, SQL native user accounts will need to be re-mapped. Add a command like the following to the *end* of your restore script:
ALTER USER [username] WITH LOGIN = [username], DEFAULT_SCHEMA=[dbo]