I have to restore production copies of my database daily onto development servers. Since the restore process requires exclusive access to the database, I have come up with this nifty script to silently kill all users connected to the database. This procedure kills all database processes before restoring the database so that the restore process gets exclusive access to the database:
CREATE proc rp_kill_db_processes
(@dbname varchar(20))
as
Declare @dbid int,
@spid int,
@str nvarchar(128)
select @dbid = dbid from master..sysdatabases
where name = @dbname
declare spidcurs cursor for
select spid from master..sysprocesses where dbid = @dbid
open spidcurs
fetch next from spidcurs into @spid
While @@fetch_status = 0
Begin
Select @str = 'Kill '+convert(nvarchar(30),@spid)
exec(@str)
--print @str
fetch next from spidcurs into @spid
End
Deallocate spidcurs
GO
Usage:
exec rp_kill_db_processes where 'test'
...where test is the name of the database.
Reader Feedback
Sam B. writes: I have created the procedure successfully, when I check the syntax of the exec line in Query Analyser I get an error near "Where". I have changed the 'test' to reflect the name of my database but still have no success. Please can you help? I must be missing something obvious!
For More Information
- What do you think about this tip? E-mail the editor at
Requires Free Membership to View
- tdichiara@techtarget.com with your feedback.
- The Best SQL Server Web Links: tips, tutorials, scripts, and more.
- Have an SQL Server tip to offer your fellow DBAs and developers? The best tips submitted will receive a cool prize--submit your tip today!
- Ask your technical SQL Server questions--or help out your peers by answering them--in our live discussion forums.
- Check out our Ask the Experts feature: Our SQL, Database Design, Oracle, SQL Server, DB2, metadata, and data warehousing gurus are waiting to answer your toughest questions.
This was first published in October 2003

Join the conversationComment
Share
Comments
Results
Contribute to the conversation