How to Kill All Processes That Have Open Connection in a SQL

The below code block can be used to kill all the processes which are connected to the database named @dbname except the process that the code block is running in the scope of. You can also set the database name by the DB_NAME() property.

DECLARE @dbname nvarchar(50)
DECLARE @SPId int

SET @
dbname = N'Works'
--SET @
dbname = DB_NAME()
DECLARE my_cursor CURSOR FAST_FORWARD FOR
SELECT SPId FROM MASTER..SysProcesses
WHERE DBId = DB_ID(@DatabaseName) AND SPId <> @@SPId

OPEN my_cursor

FETCH NEXT FROM my_cursor INTO @SPId

WHILE @@FETCH_STATUS = 0
BEGIN
KILL @SPId

FETCH NEXT FROM my_cursor INTO @SPId
END

CLOSE my_cursor
DEALLOCATE my_cursor

No comments:

Post a Comment

Please Provide your feedback here