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 first published in October 2003

Dig deeper on SQL Server and .NET development

0 comments

Oldest 

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to:

SearchCloudComputing

SearchSoftwareQuality

SearchSOA

TheServerSide

SearchCloudApplications

Close