Kill all connections to a database in SQL Server

by Viktor 19. May 2010 08:32
When you want to rename a database or something like that you need to get exclusive access to the database and it can be hard to get this exclusive access because there are always someone who has a connection. This script will kill all connections to a database, just replace "DATABASE_NAME" with the name of the database you want to kill connections for,
DECLARE @SQL VARCHAR(8000)
 
SELECT @SQL=COALESCE(@SQL,'')+'Kill '+CAST(spid AS VARCHAR(10))+ '; ' 
FROM sys.sysprocesses 
WHERE DBID=DB_ID('DATABASE_NAME')
 
EXEC(@SQL) 

Tags: ,

blog comments powered by Disqus

Creative Commons License
This work is licensed under a Creative Commons Attribution-Share Alike 2.5 Sweden License.


Welcome to the Dropit blog!

Here we, the people that work at Dropit, will write about stuff that interests us. For example web development, especially with .NET and EPiServer - but we'll also talk about other techniques that interest us, marketing on the web, social phenomenons, pop culture, games and software development in general.