Technical Article

Kill all Connections

,

There are times you want to kill all the connections in a database. This would do that trick.

This can be very useful when you replace a database regularly and some connections still exist so your automated restore fails. You can issue this command to kill all the connections before issuing a restore command.

CREATE PROC Kill_Connections (@dbName varchar(128))
as
DECLARE @ProcessId varchar(4)
DECLARE CurrentProcesses SCROLL CURSOR FOR
select spid from sysprocesses where dbid = (select dbid from sysdatabases where name = @dbName ) order by spid 
FOR READ ONLY
OPEN CurrentProcesses
FETCH NEXT FROM CurrentProcesses INTO @ProcessId
WHILE @@FETCH_STATUS <> -1
BEGIN
--print 'Kill ' + @processid
Exec ('KILL ' +  @ProcessId)
--Kill @ProcessId
FETCH NEXT FROM CurrentProcesses INTO @ProcessId
END
CLOSE CurrentProcesses
DeAllocate CurrentProcesses

Rate

You rated this post out of 5. Change rating

Share

Share

Rate

You rated this post out of 5. Change rating