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 '