Restore failure solution due to database usage when restoring database __ Database

Source: Internet
Author: User
When restoring a database, you encounter the following error solution:

System.Data.SqlClient.SqlError: Cannot obtain exclusive access to a database because the database is in use. (MICROSOFT.SQLSERVER.SMO)

1. A more direct restart of the SQL Server service, this scenario is suitable for the general personal computer, or computer only this important database use;

2. If the database is a server, there are many important databases, it is not possible because a database of all the database connections are broken, you can use the following scenario

Create the following stored procedure in the master database: Clears all sessions that use the database;

Use master
go
CREATE PROC [dbo].[ Sp_cleardbconnections]  
        @DbName    VARCHAR
AS--clears all database connections for a database  
    DECLARE @SPID    INT  
    DECLARE @SqlForClear    NVARCHAR (MB)  
      
    DECLARE Curid CURSOR forward_only for (  
        SELECT SPID  
        From Master.dbo.SysProcesses  
        WHERE db_name (DBID) = @DbName)  
    OPEN curid  
    FETCH NEXT from Curid into @SPID C16/>while @ @Fetch_Status = 0  
    BEGIN  
        SET @SqlForClear = N ' KILL ' + Cast (@SPID as NVARCHAR)  
        EXEC Sp_execu Tesql @SqlForClear  
        IF @ @Error = 0  
            PRINT ' cleared connection: ' + Cast (@SPID as VARCHAR)  
        FETCH NEXT from Curid into @S PID End Close  
    curid  
    deallocate curid  
    PRINT ' for database ' + @DbName + ' ' connection cleanup operation completed '
go

It then executes the stored procedure, clears all connections that use the database, restores it again (the duration of the operation Gap is as short as possible and avoids connecting in this gap);

EXEC sp_cleardbconnections ' database name to restore '



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.