HiveBrain v1.2.0
Get Started
← Back to all entries
debugsqlMinor

Unable to restore database backup because it is accessed by other connection

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
unableotherdatabasebecauseaccessedrestoreconnectionbackup

Problem

--first command

use master

Go
-- second command
ALTER DATABASE MyDB SET SINGLE_USER WITH ROLLBACK IMMEDIATE 

Go 
-- Third command
RESTORE DATABASE [MyDB] FROM  DISK = N'D:\Restore_Backup\Restore_05042015\AcctDB.bak' 
WITH  FILE = 1,  
MOVE N' AcctDB ' 
TO N'D:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\WFStageAcct.mdf',  
MOVE N' AcctDB _log' 
TO N'D:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\WFStageAcct_log.ldf',  
NOUNLOAD,  
REPLACE,  
STATS = 10

GO

--forth command

ALTER DATABASE MyDB SET MULTI_USER 

Go


I run the above commands, one by one to restore database in different server. But sometime I cannot restore the database after changed to single user mode, because it is accessed by other connection. If I run the whole script except the last part together would that block other connection so I will be the only user?

Solution

Running this all at once does not guarantee that no one will open a connection between you putting it in single-user mode and you starting the restore. Instead, you can put the database in offline mode rather of single-user mode to avoid this problem.

E.g.

ALTER DATABASE MyDB SET OFFLINE WITH ROLLBACK IMMEDIATE;

Code Snippets

ALTER DATABASE MyDB SET OFFLINE WITH ROLLBACK IMMEDIATE;

Context

StackExchange Database Administrators Q#101917, answer score: 6

Revisions (0)

No revisions yet.