Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

restore sql server from .bak file Exclusive access could not be obtained

I am trying to restore my sql using bak file

I am getting error

Exclusive access could not be obtained because the database is in use

I tried

USE [master]
ALTER DATABASE myDB
SET SINGLE_USER WITH ROLLBACK IMMEDIATE;

and run the query

USE [master] RESTORE DATABASE  myDB
   FROM DISK = 'C:\MyDatabase.bak' WITH  FILE = 1,  NOUNLOAD,  STATS = 10

I also tried from restore wizard with same result.

Exclusive access could not be obtained because the database is in use.

like image 887
baaroz Avatar asked Oct 14 '13 17:10

baaroz


2 Answers

Method 1

    declare @sql as varchar(20), @spid as int

    select @spid = min(spid)  from master..sysprocesses  where dbid = db_id('<database_name>')  and spid != @@spid    

    while (@spid is not null)

    begin

    print 'Killing process ' + cast(@spid as varchar) + ' ...'

    set @sql = 'kill ' + cast(@spid as varchar)

exec (@sql)

select 

    @spid = min(spid)  

from 

    master..sysprocesses  

where 

    dbid = db_id('<database_name>') 

    and spid != @@spid
 end 

 print 'Process completed...'

Method 2

  alter database database_name
  set offline with rollback immediate
  alter database database_name
  set online

go

like image 131
MAS Avatar answered Sep 29 '22 00:09

MAS


Don't need to write any query to solve this problem. I had the same problem several times and solve it by this method: when you are restoring database

  1. Go to Option tab in Restore database window
  2. Check (Overwrite the existing database (WITH REPLACE))
  3. Check (Close existing connections to destination database)
  4. Then click OK

Restore database is starting...

like image 31
Hamed Rezaei Avatar answered Sep 28 '22 22:09

Hamed Rezaei