Tip

SQL script to kill all database processes

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

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
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
Sort by: OldestNewest

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:

Disclaimer: Our Tips Exchange is a forum for you to share technical advice and expertise with your peers and to learn from other enterprise IT professionals. TechTarget provides the infrastructure to facilitate this sharing of information. However, we cannot guarantee the accuracy or validity of the material submitted. You agree that your use of the Ask The Expert services and your reliance on any questions, answers, information or other materials received through this Web site is at your own risk.