Thursday, June 14, 2012

After much searching, finally found someone who could "power set offline" a sql server database. Our prod environment has several web services that continually connect to the database and once present, keep the connection open. I don't have control over those, which leaves me with the pain of restoring backups with connections that just won't shut up. Every where you look has the alter database code for setting single user. This won't work always.  So I'm pointing you to The Intraweb Home of Andy White who created the following script. Much like he did, I want easy access to this. That guy is my hero. Impossible to hunt down and kill the 30ish respawing connections the way I was trying.

-- Kill all processes connected to a database.
use master;
declare @DatabaseName varchar(50);
declare @Spid varchar(20);
declare @Command varchar(50);
set @DatabaseName = 'MyDatabase';
print 'This query''s SPID: ' + convert(varchar, @@spid);
-- Select all SPIDs except the SPID for this connection
declare SpidCursor cursor for
select spid from master.dbo.sysprocesses
where dbid = db_id(@DatabaseName)
and spid != @@spid
open SpidCursor
fetch next from SpidCursor into @spid
while @@fetch_status = 0
begin
    print 'Killing process: ' + rtrim(@spid);
    set @Command = 'kill ' + rtrim(@spid) + ';';
    print @Command;
    execute(@Command);
    fetch next from SpidCursor into @spid
end
close SpidCursor
deallocate SpidCursor

No comments: