Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2005 Forums
 Transact-SQL (2005)
 kill all connection to single database

Author  Topic 

waterduck
Aged Yak Warrior

982 Posts

Posted - 2010-05-03 : 01:52:58
hi all, may i know how to kill all connection to a database? master..sysprocesses only shows those query that have (use databasea) but how i facing query that have linking to databasea


Hope can help...but advise to wait pros with confirmation...

PeterNeo
Constraint Violating Yak Guru

357 Posts

Posted - 2010-05-03 : 02:41:29
If u set the DB to single user mode it ll terminate all the connections.
or try this
CREATE PROCEDURE usp_killDBConnections @DBName varchar(50), @withmsg bit=1
AS
SET NOCOUNT ON
DECLARE @spidstr varchar(8000)
DECLARE @ConnKilled smallint
SET @ConnKilled=0
SET @spidstr = ''

IF db_id(@DBName) < 4
BEGIN
PRINT 'Connections to system databases cannot be killed'
RETURN
END

SELECT @spidstr=coalesce(@spidstr,',' )+'kill '+convert(varchar, spid)+ '; '
FROM master..sysprocesses WHERE dbid=db_id(@DBName)

IF LEN(@spidstr) > 0
BEGIN
EXEC(@spidstr)

SELECT @ConnKilled = COUNT(1)
FROM master..sysprocesses WHERE dbid=db_id(@DBName)

END

IF @withmsg =1
PRINT CONVERT(VARCHAR(10), @ConnKilled) + ' Connection(s) killed for DB ' + @DBName
GO


"There is only one difference between a dream and an aim.
A dream requires soundless sleep to see,
whereas an aim requires sleepless efforts to achieve..!!"
Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2010-05-03 : 11:06:39
i just want to kill all connection to a database but not all the database...when there are person accessing the database, we cant alter the restrict access to single_user therefore changing the user mode couldn't help


Hope can help...but advise to wait pros with confirmation...
Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2010-05-03 : 21:04:03
maybe my question was not clear
declare @sql varchar(max) set @sql=''
select @sql = 'kill ' + cast(spid as varchar) + ';' from master..sysprocesses where spid >50 and spid <> @@spid and db_name(dbid) = 'databaseA'

above query would kill all connection for databaseA but not following query
use databaseB;
select * from databaseA..table1


Hope can help...but advise to wait pros with confirmation...
Go to Top of Page

waterduck
Aged Yak Warrior

982 Posts

Posted - 2010-05-03 : 23:17:30
lol, my bad i forgot to rtm about with rollback immediate


Hope can help...but advise to wait pros with confirmation...
Go to Top of Page
   

- Advertisement -