Sql-server – Can’t restore sql bak file to a new database

restoresql serversql-server-2012

I can't seem to restore a bak file to the same server but a new database. It works fine if I do it on another computer. I use SQL Server 2012 through SSMS. Everytime I do it it says Exclusive access could not be obtained because the database is in use, even though it's a nonexistent destination database.

Here are the steps:

  1. Right click Databases
  2. Restore Database…
  3. [General] Source from Device, select the bak file
  4. [General] Change the Destination database name to a new name
  5. [Files] Change mdf and ldf Restore As paths to a different, new path
  6. [Options] (unnecessary on the other computer) Check Overwrite the existing database (WITH_REPLACE)
  7. [Options] (unnecessary on the other computer) Check Close existing connections to destination database
  8. Click OK

This is the error message:

Restore of database 'DELVIPROD_JUNE' failed.
(Microsoft.SqlServer.Management.RelationalEngineTasks)

Additional information:
System.Data.SqlClient.SqlError:Exclusive access could not be obtained because the database is in use.
(Microsoft.SqlServer.SmoExtended)

Best Answer

Close all tabs on the right side in the management studio and try again. It is possible that you clicked on the database and some tab on the right side is accessing it.

Alternatively, you may use this sql (replace file name and path)

USE master;
GO
ALTER DATABASE DELVIPROD_JUNE SET SINGLE_USER WITH ROLLBACK IMMEDIATE;
restore database DELVIPROD_JUNE FROM DISK = 'C:\temp\db.bak'   WITH replace 
ALTER DATABASE DELVIPROD_JUNE SET MULTI_USER;

If you want to make a copy of a database, this might help https://serverfault.com/questions/62590/how-to-duplicate-mssql-database-on-the-same-or-another-server