SQL-Server: Error - Exclusive access could not be obtained because the database is in use

后端 未结 14 2488
隐瞒了意图╮
隐瞒了意图╮ 2020-12-12 17:45

I am actually trying to make a script (in Sql Server 2008) to restore one database from one backup file. I made the following code and I am getting an error -



        
相关标签:
14条回答
  • 2020-12-12 18:11

    For me, the solution is:

    1. Check Overwrite the existing database(WITH REPLACE) in optoins tab at left hand side.

    2. Uncheck all other options.

    3. Select source and destination database.

    4. Click ok.

    That's it.

    0 讨论(0)
  • 2020-12-12 18:11

    Use the following script to find and kill all the opened connections to the database before restoring database.

    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...'
    

    Hope this will help...

    0 讨论(0)
  • Solution 1 : Re-start SQL services and try to restore DB Solution 2 : Re-start system / server and try to restore DB Solution 3 : Take back of current DB, Delete the current/destination DB and try to restore DB.

    0 讨论(0)
  • 2020-12-12 18:13

    Setting the DB to single-user mode didn't work for me, but taking it offline, and then bringing it back online did work. It's in the right-click menu of the DB, under Tasks.

    Be sure to check the 'Drop All Active Connections' option in the dialog.

    0 讨论(0)
  • 2020-12-12 18:16
    Use Master
    alter database databasename set offline with rollback immediate;
    
    --Do Actual Restore
    RESTORE DATABASE databasename
    FROM DISK = 'path of bak file'
    WITH MOVE 'datafile_data' TO 'D:\newDATA\data.mdf',
    MOVE 'logfile_Log' TO 'D:\newDATA\DATA_log.ldf',replace
    
    alter database databasename set online with rollback immediate;
    GO
    
    0 讨论(0)
  • 2020-12-12 18:19

    I just restarted the sqlexpress service and then the restore completed fine

    0 讨论(0)
提交回复
热议问题