James Ray Anderson

James Ray Anderson
James Ray Anderson
0 comments

Restore Fails...Exclusive Access could not be obtained

5:00 AM
The Error
Ever get the following error when restoring a database in SQL Server

Restore failed for server . (Microsoft.SqlServer.Smo). Exclusive access could not be obtained because the database is in use.

The Cause
This error occurs when you try to restore a database or log while the database is in use, by any user, including yourself.

The Quick Fix
For my development environment I just took the database offline, closed all open query windows, and put it online. However, you may have a more difficult case in which you need to restrict access. Here is a good code snippet.

USE Master
ALTER DATABASE SET SINGLE_USER With ROLLBACK IMMEDIATE;
GO
RESTORE DATABASE FROM DISK = 'C:\Program Files\Microsoft SQL Server\MSSQL\BACKUP\.bak';
GO
ALTER DATABASE SET MULTI_USER;
GO

Break Down
What this does:
  • Uses the master so that your query window is not interacting with
  • Sets the "single user" option, with the "rollback immediate" to close any incomplete transactions. This includes users with connections to the database that also need an exclusive lock.
  • Performs the restore.
  • Sets the database back to multi-user

Hope this helps!


0 comments:

 
Toggle Footer
Top