When restoring a database backup, the following error occurs: Because the database is in use, you cannot obtain exclusive access to the database.
Solution: modify some database names and execute the SQLCodeAnd then restore it immediately.
Use Master
Declare @ Dbname Varchar ( 20 )
Set @ Dbname = ' Dfd_test ' -- -This is the database name.
Declare @ SQL Nvarchar ( 500 )
Declare @ Spid Int -- The spid value is a unique integer assigned to the connection when the user connects.
Set @ SQL = ' Declare getspid cursor
Select spid from sysprocesses where dbid = db_id ( ''' + @ Dbname + ''' ) '
Exec ( @ SQL )
Open Getspid
Fetch Next From Getspid Into @ Spid
While @ Fetch_status <>- 1 -- If the fetch statement does not fail to be executed or this row is not in the result set.
Begin
Exec ( ' Kill ' + @ Spid ) -- Terminate normal connection
Fetch Next From Getspid Into @ Spid
End
Close Getspid
Deallocate Getspid