The Darkside

Shedding light on things and stuff

 
  Home :: Contact :: Syndication  :: Login
  75 Posts :: 0 Stories :: 49 Comments :: 2 Trackbacks

Ads

Archives

Post Categories

Open Source Projects

Other Blogs

If you're using a database in any of your unit tests (or dropping/recreating) on a regular basis, you'll inevitably get an error alongs the lines of "Cannot drop database 'Test' because it's in use".

I've created this stored proc on my master DB which allows me to quickly kill all processes on a database. I originally got the idea from a post on the net some time back, but I honestly can't remeber who from. If it's yours, drop me a mail and I'll attribute the idea accordingly :)

CAUTION: There is no "Are you sure?" message. Processes are killed. Quickly. 

 Expand Code
USE MASTER
GO
IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[sp_KillDatabaseProcesses]') AND type in (N'P', N'PC'))
DROP PROCEDURE [dbo].[sp_KillDatabaseProcesses]
GO
CREATE PROCEDURE dbo.sp_KillDatabaseProcesses
( @databaseName varchar(100))
 
AS
 
DECLARE @databaseId int,
        @sysProcessId int,
        @cmd varchar(1000)
 
EXEC ('USE MASTER')
 
SELECT @databaseId = dbid FROM master..sysdatabases
  WHERE [name] = @databaseName
 
DECLARE sysProcessIdCursor CURSOR FOR
   SELECT spid FROM [master]..[sysprocesses] WHERE [dbid] = @databaseId
OPEN sysProcessIdCursor
FETCH NEXT FROM sysProcessIdCursor INTO @sysProcessId
WHILE @@fetch_status = 0
  BEGIN
    SET @cmd = 'KILL '+ convert(nvarchar(30),@sysProcessId)
    PRINT @cmd
    EXEC(@cmd)
    FETCH NEXT FROM sysProcessIdCursor INTO @sysProcessId
END
DEALLOCATE sysProcessIdCursor            
GO
posted on Friday, August 08, 2008 11:56 AM
Comments have been closed on this topic.