Thursday, July 7, 2016

Kill connections to a SQL Server Database


Offen we encounter the failure message when trying to restore that database is in use. One solution is to bring the database into single user mode, but that will leave you with the database being in single user mode until you put it back to multi user mode.

The below query is used to kill the existing connections and when you paste your query below the cursor it will run your query immediately after the existing connections are killed.


** Replace the string with you Database name


 Declare @Dbname varchar(50)

 Set @DBname ='<DBNAME>'

create table ##killconnections (Command varchar(15))

insert ##killconnections (command )
select 'KILL ' + cast (spid as char(4))
from master..sysprocesses p
inner join master..sysdatabases d on p.dbid = d.dbid
where d.name = @DBName


declare @KILLSTMT varchar(15)
declare killcsr cursor for
select * from ##killconnections


open killcsr
fetch next from killcsr into @KILLSTMT
while @@fetch_status = 0
begin

exec (@KILLSTMT)
fetch next from killcsr into @KILLSTMT
end

deallocate killcsr
drop table ##killconnections