How to kill all sessions that have open connection in a SQL Server Database?

As SQL Server DBAs, many times we need to KILL all Open Sessions against the SQL Server Database to proceed with Maintenance Task, Restore and more…

You can use below different techniques to KILL all open sessions against the database.

Technique – I
Here we will query the SysProcesses table to get the session running against the user database and prepare the dynamic SQL statement to KILL all the connection.

view source

print?

01

DECLARE @DbName nvarchar(50)

02

SET @DbName = N’Write a DB Name here’

03

 

04

DECLARE @EXECSQL varchar(max)

05

SET @EXECSQL = ”

06

 

07

SELECT @EXECSQL = @EXECSQL + ‘Kill ‘ + Convert(varchar, SPId) + ‘;’

08

FROM MASTER..SysProcesses

09

WHERE DBId = DB_ID(@DbName) AND SPId @@SPId

10

 

11

EXEC(@EXECSQL)

Technique – II
Take the database into Single User Mode and execute all the task needs to perform against the databse.

view source

print?

1

ALTER DATABASE [Database Name] SET SINGLE_USER WITH ROLLBACK IMMEDIATE

Once you are finish with all the required task make the database accessible to everyone.

view source

print?

1

ALTER DATABASE [Database Name] SET MULTI_USER

Technique – III
In case of restore the database by replacing existing database, you can take the database OFFLINE and restore it. Restore will bring the database online.

view source

print?

1

ALTER DATABASE [Database Name] SET OFFLINE WITH ROLLBACK IMMEDIATE

view source

print?

1

ALTER DATABASE [Database Name] SET ONLINE

Technique – IV
Go to Activity Monitor, Select the desired database and right click on the database to KILL the process.

clip_image001

 

Source: How to kill all sessions that have open connection in a SQL Server Database? « SQLDBPOOL.COM