When your got the below SQL error for restore.
Exclusive access could not be obtained because the database is in use.
For resolve this issue,
We can kill the users or change DATABASE in Single user mode to disconnect them.
1. Kill users
You can check current online users by "sp_who2" command.
Then kill the command by SPID
The example is SPID has 333 and "kill 333" then it will kill the process.
Here is example for hostname start with A or J or R to kill. And not kill myself.
DECLARE @kill varchar(8000) = '';
SELECT @kill = @kill + 'kill ' + CONVERT(varchar(5), spid) + ';'
FROM master..sysprocesses
WHERE spid <> @@spid AND (hostname like 'A%' OR hostname like 'J%' OR hostname like 'R%')
EXEC(@kill);
2. change DATABASE in single user mode
here is example for AdventureWorks DB, change name
ALTER DATABASE AdventureWorks SET SINGLE_USER WITH ROLLBACK IMMEDIATE GO RESTORE DATABASE AdventureWorks FROM DISK = 'C:\AdventureWorks.BAK' GO
After restore you may need to add below code to change back mode.
ALTER DATABASE AdventureWorks SET MULTI_USER
Go
Comments
Post a Comment