Sql-server – Error in restore database

sql serversql-server-2008-r2stored-procedures

I use this query in SQL Server 2008 R2 to restore DB1 database:

RESTORE DATABASE [DB1] 
FROM DISK = N'D:\new.bak' 
WITH RESTRICTED_USER, FILE = 1, NOUNLOAD, REPLACE, STATS = 10;

The following error is displayed:

Msg 3102, Level 16, State 1, Line 1
RESTORE cannot process database 'DB1' because it is in use by this session. It is recommended that the master database be used when performing this operation.
Msg 3013, Level 16, State 1, Line 1
RESTORE DATABASE is terminating abnormally.

Best Answer

The message seems pretty clear: you cannot be using the DB1 database when trying to restore it - instead, use the master database!

So in SQL Server Management Studio, first close all windows that are open and using that database! Then run this:

USE master
GO

RESTORE DATABASE [DB1] 
FROM DISK = N'D:\new.bak' 
WITH RESTRICTED_USER, FILE = 1, NOUNLOAD, REPLACE, STATS = 10;