Search This Blog & Web

Thursday, March 17, 2011

Drop User connections of Running Database in SQL SERVER .


Drop all connections by using Following Query

USE master
GO

ALTER DATABASE DBName
SET OFFLINE WITH ROLLBACK IMMEDIATE
ALTER DATABASE DBName
SET ONLINE

You can kill all the processes using a database with this code:

USE master
go

DECLARE @dbname sysname

SET @dbname = 'Database'

DECLARE @spid int
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname)
WHILE @spid IS NOT NULL
BEGIN
EXECUTE ('KILL ' + @spid)
SELECT @spid = min(spid) from master.dbo.sysprocesses where dbid = db_id(@dbname) AND spid > @spid
END

Remember you cannot kill System connections with second command.

No comments: