Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill/Terminate all running process on Sql Server 2008

After executing this query on master db ,it is giving me all running process on all databases, is there any query which will kill all process running on a database .

USE
Master
GO

SELECT
SPID,DBID FROM SYSPROCESSES
WHERE
DBID NOT IN (1,2,3,4) AND SPID >50 AND SPID<> @@spid   
like image 296
Buzz Avatar asked Jun 11 '12 07:06

Buzz


2 Answers

If you want to force every other connection to disconnect, and you have suitable permissions, you can bounce the database in and out of single user mode:

alter database current set single_user with rollback immediate;
go
alter database current set multi_user;
go

Any other connection to the same database will be terminated.

like image 97
Damien_The_Unbeliever Avatar answered Oct 25 '22 21:10

Damien_The_Unbeliever


Please see below SQL script to kill all processes for a given Database (SQL Server 2014)

Declare @DbName nvarchar(60)='YourDBName'  
Declare @SPID int  

--get all processes  
DECLARE @Table TABLE(  
    SPID INT,  
    Status VARCHAR(MAX),  
    LOGIN VARCHAR(MAX),  
    HostName VARCHAR(MAX),  
    BlkBy VARCHAR(MAX),  
    DBName VARCHAR(MAX),  
    Command VARCHAR(MAX),  
    CPUTime INT,  
    DiskIO INT,  
    LastBatch VARCHAR(MAX),  
    ProgramName VARCHAR(MAX),  
    SPID_1 INT,  
    REQUESTID INT  
)  

INSERT INTO @Table EXEC sp_who2  
--using cursor to kill all processes  
Declare cur_KillAllProcesses CURSOR FAST_FORWARD FOR  
Select   
SPID  
From @Table  
WHERE DBName=@DbName  
OPEN cur_KillAllProcesses  

FETCH NEXT FROM cur_KillAllProcesses INTO   
@SPID  

WHILE @@FETCH_STATUS=0  
BEGIN  

--add kill process command  

Exec('KILL '+ @SPID)  


FETCH NEXT FROM cur_KillAllProcesses INTO @SPID  

END  

CLOSE cur_KillAllProcesses  
DEALLOCATE cur_KillAllProcesses   
like image 29
Satbir Avatar answered Oct 25 '22 22:10

Satbir