SQL script to kill all database processes

This SQL script will silently kill all users connected to a SQL Server database.

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 SQL 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 used this SQL script to create the procedure, successfully, but 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!


This was last published in October 2003

Start the conversation

Send me notifications when other members comment.

By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Please create a username to comment.

-ADS BY GOOGLE

SearchCloudComputing

SearchSoftwareQuality

SearchSOA

TheServerSide

SearchCloudApplications

Close